Warm tip: This article is reproduced from stackoverflow.com, please click
dataframe for-loop r subset

for loop to create data frames which are subsets of another data frame

发布于 2020-04-03 23:42:24

I'm trying to create a for loop that creates subsets of my original data

Right now I create subsets as follows:

Dataset_1 <- subset(Dataset1, compliance>=0)    
Dataset_2 <- subset(Dataset1, compliance>=5) 
Dataset_3 <- subset(Dataset1, compliance>=10)
Dataset_4 <- subset(Dataset1, compliance>=15)
Dataset_5 <- subset(Dataset1, compliance>=20)
Dataset_6 <- subset(Dataset1, compliance>=25)

However, I would like to use a for loop to do this and was thinking something like this might work:

Dataset_ = {}
for (i in 1:6){
  Dataset_[[i]] = subset(Dataset1, compliance>=(0+(i-1)*5))
}

When I do this, I get a list with data frames in it. However, I was wondering whether there is a way to write the for loop so that the data frames are not put in a list but instead made as individual data frames. Reason: I would like to save the data frames that are created as .Rdata files in a folder e.g.:

save(Dataset_2, file = "Hypothesis1/Dataset1.RData")
save(Dataset_3, file = "Hypothesis1/Dataset2.RData")
save(Dataset_4, file = "Hypothesis1/Dataset3.RData")
Questioner
Jeroen
Viewed
90
ulfelder 2020-01-31 20:35

You don't need to create a list. You can just write the files directly to disk within your for loop as follows:

for (i in seq(6)) {

  save(subset(Dataset1, compliance >= (0 + (i-1) * 5)),
       file = sprintf("Hypothesis1/Dataset%s.RData", i))

}