1

Using R base, I would like to convert a data.frame into a nested list while keeping the name of the data unchanged. Below is my sample code. Thank you.

#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 = "-"))),]))
2
  • 1
    Doesn't work for me: object 'DATE' not found Commented Jul 2, 2017 at 19:06
  • object DATE not found, there's an error in your code. And can't you provide a smaller example ? Otherwise, DF[[i]] <- looks useless. Commented Jul 2, 2017 at 19:25

1 Answer 1

3

You don't need DF.NEW nor DF[[i]] <- lapply(...). Just do

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 = "-"))),]))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.