Sebastian Zeki Sebastian Zeki - 20 days ago 7
R Question

grep from a list to produce multiple dataframes

I have a dataframe with unique values in it as follows

red
green
blue
yellow


I have another dataframe with colours and other columns as follows

red 1 4
green 2 4
blue 2 5
yellow 1 7
red 54 35
green 25 54
blue 33 66
yellow 63 63
blue 22 99
yellow 80 25
red 26 33
green 16 17


I need to create dataframes which are the result of grepping out the rows with each colour (with the dataframe named by colour eg:

dfred
red 1 4
red 54 35
red 26 33
dfyellow
yellow 1 7
yellow 63 63
yellow 80 25

dfblue
blue 2 5
blue 33 66
blue 22 99

dfgreen
green 2 4
green 25 54
green 16 17


I could do this one by one by think there's an easier way. Can this be done in a function?

I really don't know how to substitute each grep phrase into a function that would output such a named dataframe

Answer

We can do this with split to create a list of data.frames

lst <- split(df2, as.character(df2$col1))
names(lst) <- paste0('df', names(lst))

and then with list2env create the individual objects in the global environment (not recommended though)

list2env(lst, envir = .GlobalEnv)
dfred
#   col1 col2 col3
#1   red    1    4
#5   red   54   35
#11  red   26   33