如何在不强制转换为数字的情况下迭代日期列表? [英] 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 对象列表的首选方法是什么?
- 我不明白约书亚的回答(从上面链接的问题中接受的答案),我会在这里引用它:所以你的
Date
向量被强制为numeric
因为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
输入强制转换为 numeric
,因为正如@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
或 应用
.如果您有一个非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
.
了解更多信息的资源
如果您想更深入地研究向量,可以从 John Cook 的笔记开始,继续R Inferno,继续SDA.
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屋!