问题
I have one dataframe, and I would like to make a list of dataframes, each of which is a subset of this original data, based on the value of one variable.
I have found this answer on CrossValidated https://stats.stackexchange.com/questions/161414/creating-subsets-of-dataframes-from-a-single-dataframe-based-on-the-distinct-val It looks like he's applying a different function to create his new dataframes than I would like to, and I'm not sure how to make this work for what I would like to do.
Here is the example of what I would like to do:
months <- c(0:35)
product<- c(112:147)
index <- rnorm(36)
data <- data.frame(months, product, index)
subfun<-function(x,y,z) { subset(x,y>=z & y<=z+12) }
for(i in 1:24)
{
assign(paste("dataset",i-1,i+11,sep=""),subfun(data, data$months,i-1))
i=i+1
}
This gives me 26 separate dataframes, each with a unique name. I would like to have these as a list, so I can use lapply to apply a regression function to each separate dataframe (dataset012:dataset236).
Is anyone able to tell me how I can make a list of dataframes from the outset? I don't want to create all the dataframes separately, but instead create a list of dataframes when I do the subsetting.
I hope this is clear, thanks very much for your help.
来源:https://stackoverflow.com/questions/42475660/making-a-list-of-dataframes-which-are-a-subset-of-one-dataframe-using-r