문제 설명
R 목록을 벡터로 바꾸는 방법과 목록이 필요한 이유 (R how to turn lists to vectors, and why a list at all)
관심 있는 날짜를 벡터에 추가하는 간단한 루프를 만드는 날짜 벡터를 만들고 싶습니다. 그러나 어떤 이유로 목록으로 바뀝니다.
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]
목록을 벡터로 바꾸는 표준 접근 방식은 저를 위해 unlist()
를 사용하는 것이지만 이것은 어떤 이유로 여기에서 작동하지 않습니다. 저를 위한 유일한 작업 방법은 여기에 있는 이 복잡한 버전이었습니다.
tmp <‑ as.Date(as.data.frame(t(as.data.frame(listOfHolidays)))$V1)
그래서 제 질문은 아주 기본적인 것입니다. 1. 왜 갑자기 목록이 됩니까? 2. 좀 더 우아한 방식으로 일반 벡터로 변경하는 방법.
참조 솔루션
방법 1:
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]
방법 2:
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]
(by kEks、ThomasIsCoding、iod)