I'm trying to get a for loop to generate multiple smaller dataframes from a large dataframe:
Year <- rep(1995:2012,4)
Name <- rep(LETTERS[1:4],18)
abc <- data.frame(Year,Name)
for (year in 1995:2012) {
assign(paste("dff",year,sep=""), abc[abc$Year == year,])
#paste("dff",year,sep="") <- paste("dff",year,sep="")[with(paste("dff",year,sep=""), order(Name)), ]
}
Problem is the last (commented) line which when uncommented throws an error:
invalid 'envir' argument of type 'character'.
What can I do to fix this? I'm basically trying to order the dataframe by the column Name.
<-assignment to a character string resulting frompaste. (You didn't do it in the line above---you usedassignfor that purpose!) A couple ideas: (a) sort the data frame byNamebefore the loop. (b) Use a list of data frames instead:abc_list = split(abc, abc$Year)and then to sort:abc_list = lapply(abc_list, function(x) x[order(x$Name), ]). See, e.g., how to make a list of data frames.