EcologyTom EcologyTom - 3 months ago 12
R Question

Split dataframe to multiple small dataframes in R

I have a large dataframe I would like to split into multiple small data frames, based on the value in the

Name
column.

head(DATAFILE)

# Age Site Name 1 2 3 4 5

# 10 1 Orange 0 2 1 0 1
# 10 1 Apple 2 5 4 0 2
# 10 1 Banana 0 0 0 0 2
# 20 2 Orange 0 2 1 0 0
# 20 2 Apple 0 2 0 7 1
# 20 2 Banana 0 4 1 3 6


And an example file of the desired output;

head(Orange)

# Age Site Name 1 2 3 4 5

# 10 1 Orange 0 2 1 0 1
# 20 2 Orange 0 2 1 0 0


I have tried

SPLIT.DATA <- split(DATAFILE, DATAFILE$Name, drop = FALSE)


But this returns a large list, and I would like individual files so that I can save them as .csv files. So I would like either a better way of dividing the original file, or a way to further divide the SPLIT.DATA file.

Answer

It is better to save the datasets directly from the list output of split itself instead of creating individual objects in the global environment. We loop by the names of the 'SPLIT.DATA', and write the list elements to individual csv files with the same name as the names of the list elements by pasteing the names to .csv in the write.csv call.

lapply(names(SPLIT.DATA), function(nm) 
   write.csv(SPLIT.DATA[[nm]], paste0(nm, ".csv"), row.names = FALSE, quote = FALSE))