9lotus dmay = seq.Date(from = as.Date("2021-03-31"), to = as.Date("2021-03-01"), by = "-1 day") class(dmay[1]) # Date 使用以下方法循环返回numeric for (d in dmay) print(class(d)) 而使用下述方法,得到是Date for (i in seq_along(dmay)) print(class(dmay[i])) 哪位高手能解释一下这中间的机理吗?
yihui 日期数据本质上就是整数,只不过带了个特殊类型。一行代码看清纸老虎: > dput(as.Date("2021-03-31")) structure(18717, class = "Date") 整数的意思是以 1970-01-01 为原点的天数,即 1970 年元旦是第零天。 至于为什么 for 循环去掉了对象的类,可能得看 R 源代码。对这种现象我倒是不奇怪,因为 R 丢弃类或其它属性的行为并不罕见,比如 unique(c(a = 1)) 返回的结果会丢弃元素名字 a。
frankzhang21 9lotus format 可以直接作用于整个vector,不用循环的 format(seq.Date(from = as.Date("2021-03-31"), to = as.Date("2021-03-01"), by = "-1 day"),'%w')=="1" #> [1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE #> [13] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE #> [25] FALSE FALSE FALSE FALSE FALSE FALSE TRUE <sup>Created on 2021-04-12 by the reprex package (v1.0.0)</sup>