0

I have data that is like the following (Except that is populated by all 52 weeks). "data"

Week   State    Value 
1        CA      4
1        AL      5
1        MO      9
1        IL      12
2        NY      1
2        CA      2
2        WA      8
3        WY      9
3        SC      10

I would like to create new data.frames for every week so that I may do further analyses. How would I go about this? I tried:

for( i in 1:52) {
     DataWeeki <- data[which(data$Week==i),]
}

This creates a single dataframe of 3 variables (with the appropriate variable names) but no data.

What is the correct way to go about this?

Lucas Walz
  • 19
  • 1

1 Answers1

1

We can use split in base R to create a list of data.frames

lst1 <- split(data, data$Week)
names(lst1) <- paste0("DataWeek", 1:52)

From the list, elements can be extracted with $ or [[

lst1[["DataWeek1"]]

It is not recommended to create multiple objects in the global environment, but if we need, we can use list2env (but there would be 52 objects and not good at all)

 list2env(lst1, .GlobalEnv)

Regarding why it creates a single object is because the object gets updated in each run and what we get is the last run object. Instead, here assign is needed (not recommended)

for( i in 1:52) {
   assign(paste0("DataWeek", i), data[which(data$Week==i),])
 }

lists can also be created with for loop

lst1 <- vector("list", 52)
for(i in 1:52) {
       lst1[[i]] <- data[which(data$Week==i),]
  }
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Great! This worked. Thank you! However, all of these new dataframes created are named 1,2,3 etc. Can I have control in naming these somehow besides doing it manually? – Lucas Walz Dec 06 '19 at 04:06
  • 1
    @LucasWalz If you check my update `names(lst1) <- paste0("DataWeek", 1:52)` – akrun Dec 06 '19 at 04:07