如何在不强制转换为数字的情况下遍历日期列表? [英] How to iterate over list of Dates without coercion to numeric?
问题描述
> dates <- as.Date(c("2013-01-01", "2013-01-02"))
> class(dates)
[1] "Date"
> for(d in dates) print(class(d))
[1] "numeric"
[1] "numeric"
我有两个问题:
- 迭代访问Date对象列表的首选方法是什么?
- 我不明白约书亚(Joshua)的答案(上面链接的问题的可接受答案),在这里引用一下:因此,您的
Date
向量被强制转换为数字
,因为Date
对象不是严格的矢量".那么如何确定应将Date
强制为numeric
?
- What is the preferred way to iterate over a list of Date objects?
- I don't understand Joshua's answer (accepted answer from the question linked above), I'll quote it here: "So your
Date
vector is being coerced tonumeric
becauseDate
objects aren't strictly vectors". So how is it determined thatDate
should be coerced tonumeric
?
推荐答案
这里有两个问题.一种是输入是否从 Date
强制为 numeric
.另一个是输出是否被强制为 numeric
.
There are two issues here. One is whether the input gets coerced from Date
to numeric
. The other is whether the output gets coerced to numeric
.
输入
For循环将 Date
输入强制为数字
,因为正如@DWin和@JoshuaUlrich指出的那样, for
循环采用 vectors
和 Date
在技术上不是向量.
For loops coerce Date
inputs to numeric
, because as @DWin and @JoshuaUlrich point out, for
loops take vectors
, and Date
s are technically not vectors.
> for(d in dates) print(class(d))
[1] "numeric"
[1] "numeric"
另一方面, lapply
及其简化后代 sapply
没有这样的限制.
On the other hand, lapply
and its simplifier offspring sapply
have no such restrictions.
> sapply( dates, function(day) class(day) )
[1] "Date" "Date"
输出
但是!上面的 class()
的输出是一个字符.如果您尝试实际返回一个日期对象,则 sapply
不是您想要的.
However! The output of class()
above is a character. If you try actually returning a date object, sapply
is not what you want.
lapply
不会强制转换为向量,但是 sapply
可以做到:
lapply
does not coerce to a vector, but sapply
does:
> lapply( dates, identity )
[[1]]
[1] "2013-01-01"
[[2]]
[1] "2013-01-02"
> sapply( dates, identity )
[1] 15706 15707
这是因为 sapply
的简化函数将输出强制转换为向量.
That's because sapply
's simplification function coerces output to a vector.
摘要
因此:如果您有一个 Date
对象,并且想要返回一个非 Date
对象,则可以使用 lapply
或sapply
.如果您有一个非 Date
对象,并且想要返回一个 Date
对象,则可以使用 for
循环或 lapply
.如果您有一个 Date
对象并想返回一个 Date
对象,请使用 lapply
.
So: If you have a Date
object and want to return a non-Date
object, you can use lapply
or sapply
. If you have a non-Date
object, and want to return a Date
object, you can use a for
loop or lapply
. If you have a Date
object and want to return a Date
object, use lapply
.
了解更多信息的资源
如果您想更深入地研究向量,可以从约翰·库克的笔记开始,继续 R地狱,然后继续
If you want to dig deeper into vectors, you can start with John Cook's notes, continue with the R Inferno, and continue with SDA.
这篇关于如何在不强制转换为数字的情况下遍历日期列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!