R从Data.Frame创建嵌套列表

时间:2017-07-02 18:54:21

标签: r list dataframe nested

使用R base,我想将data.frame转换为嵌套列表,同时保持数据名称不变。以下是我的示例代码。谢谢。

#I WOULD LIKE TO SIMPLIFY THIS PROCESS
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2017-12-31"), by = "day"), NUM = c(1:3))
DF <- list(
    lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + 1, "06", "30", sep = "-"))), ]),
    lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + 2, "06", "30", sep = "-"))), ]),
    lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + 3, "06", "30", sep = "-"))), ])
)

#BUT THIS DOES NOT WORK
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2017-12-31"), by = "day"), NUM = c(1:3))
DF <- lapply(1:3, function(i) DF[[i]] <- lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + i, "06", "30", sep = "-"))),]))

#YET THIS WORKS WITH A NEW NAME
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2017-12-31"), by = "day"), NUM = c(1:3))
DF.NEW <- list()
DF.NEW <- lapply(1:3, function(i) DF.NEW[[i]] <- lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + i, "06", "30", sep = "-"))),]))

1 个答案:

答案 0 :(得分:3)

您不需要DF.NEW也不需要DF[[i]] <- lapply(...)。只是做

DF <- lapply(1:3, function(i)
    lapply(2014:2015, function(t)
    DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <=   as.Date(paste(t + i, "06", "30", sep = "-"))),]))