Search code examples
rdataframemultiple-columnscbind

combine same column from various data frames into new dataframe


I have several dataframes that look like this:

df1
Time Terrain 
1     Land
2     Land 
3     Land  
4     Land 

I want to take the column "Terrain" from each dataframe and put them all in a new one, giving the columns of the new dataframe the name of which dataframe it was extracted from. Should look like this:

combined_terrain

df1  df2  df3
Land Land Sea
Land Sea  Air
Land Sea  Land
Land Sea  Land

I know I have to use cbind but I have several dataframes and don't want to be typing each out. Do I loop it by making a list of the different dataframes?


Solution

  • Place all the datasets (assuming that it starts with 'df' followed by numbers) in a list ('lst'). Then use lapply to extract the 'Terrain' and cbind it

    setNames(do.call(cbind, lapply(lst, `[`, 'Terrain')), nm1)
    

    data

    nm1 <- ls(pattern="df\\d+")
    lst <- mget(nm1)