简体   繁体   中英

R how to turn lists to vectors, and why a list at all

I want to create a vector of dates, for which I created a simple loop which added the dates i am interested in to a vector. However, for some reason it turns it into a list.

library(timeDate)
listOfHolidays <- c()
for (year in c(getRmetricsOptions("currentYear") ,getRmetricsOptions("currentYear") +1)) {
listOfHolidays <- c(listOfHolidays,GoodFriday(year),EasterMonday(year))}

print(listOfHolidays)
[[1]]
GMT
[1] [2020-04-10]

[[2]]
GMT
[1] [2020-04-13]

[[3]]
GMT
[1] [2021-04-02]

[[4]]
GMT
[1] [2021-04-05]

The standard approach to turn a list into a vector is to use unlist() for me, however this does not work here for some reason. The only working way for me was this convoluted version here.

tmp <- as.Date(as.data.frame(t(as.data.frame(listOfHolidays)))$V1)

So my questions are quite basic. 1. Why is it suddenly a list. 2. How to I change it into a plain vector in a more elegant way.

You can try do.call + c like below

tmp <- do.call(c,listOfHolidays)

such that

> tmp
GMT
[1] [2020-04-10] [2020-04-13] [2021-04-02] [2021-04-05]

The source of the problem is that you're combining different classes of objects when you concatenate listOfHolidays with timeDate class objects. A vector has to be made of a single class of object, so combining them reverts to a list, since neither can be coerced into the other. If you'll check methods(c) you'll see that timeDate class has its own method, that's intended to allow for the creation of vectors of this class created by the timeDate package.

The way to avoid this is by doing away with the loop altogether, and combining a lapply with a do.call (as in @thomasIsCoding 's solution):

do.call(c,
       sapply(c(getRmetricsOptions("currentYear"),
                'nextYear'=unname(getRmetricsOptions("currentYear") +1)), 
       FUN=function(x) {c(goodfriday=GoodFriday(x),easter=EasterMonday(x))}))

result:

GMT
currentYear.goodfriday     currentYear.easter    nextYear.goodfriday        nextYear.easter 
          [2020-04-10]           [2020-04-13]           [2021-04-02]           [2021-04-05] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM