I am using R on a regular basis and I have stumbled above something weird:
Sys.time() |> class()
times <- Sys.time()+1:3
print(times)
for (tme in times) {
print(tme)
}
tme %in% times
This gives the output:
> Sys.time() |> class()
[1] "POSIXct" "POSIXt"
> times <- Sys.time()+1:3
> print(times)
[1] "2024-01-18 10:00:28 CET" "2024-01-18 10:00:29 CET" "2024-01-18 10:00:30 CET"
> for (tme in times) {
+ print(tme)
+ }
[1] 1705568429
[1] 1705568430
[1] 1705568431
> tme %in% times
[1] FALSE
How is such a behaviour justifiable? I find the last line especially hard to justify (tme %in% times == FALSE).
Reason behind
In
forloop, the expressiontimeswill be coerced to avector(when you see the help document by typing?`for`However, in
vector, no attribute will be retained (when typing?vectorand see the description)Workaround
To keep all the attributes, you can convert the values in
timesinto a list, for example, you can useas.list(times)inforloop like belowor you can use
sapplylike below