Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

r - How to iterate over list of Dates without coercion to numeric?

This is related to Looping over a Date or POSIXct object results in a numeric iterator

> 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"

I have two questions:

  1. What is the preferred way to iterate over a list of Date objects?
  2. 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 to numeric because Date objects aren't strictly vectors". So how is it determined that Date should be coerced to numeric?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Input

For loops coerce Date inputs to numeric, because as @DWin and @JoshuaUlrich point out, for loops take vectors, and Dates are technically not vectors.

> for(d in dates) print(class(d))
[1] "numeric"
[1] "numeric"

On the other hand, lapply and its simplifier offspring sapply have no such restrictions.

> sapply( dates, function(day) class(day) )
[1] "Date" "Date"

Output

However! The output of class() above is a character. If you try actually returning a date object, sapply is not what you want.

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

That's because sapply's simplification function coerces output to a vector.

Summary

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.

Resources for learning more

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...