Francesco Francesco - 2 months ago 6
R Question

Take a row from n dataframes and create a new dataframe with the rows taken, R

Assume I have 2 dataframes. I want to select only a row, let's say industry c3, from every dataframe and put them in another data.frame, df3.

df1 = data.frame(Industries = c("c1", "c2", "c3", "c4", "c5"), Exports = c(100, 40, 30, 10, 50), Imports =c(90,50,25,15,50))
df2 = data.frame(Industries = c("c1", "c2", "c3", "c4", "c5"), Exports = c(20, 90, 10, 30, 60), Imports =c(40,30,25,55,40))

df1
Industries Exports Imports
1 c1 100 90
2 c2 40 50
3 c3 30 25
4 c4 10 15
5 c5 50 50
df2
Industries Exports Imports
1 c1 20 40
2 c2 90 30
3 c3 10 25
4 c4 30 55
5 c5 60 40


In my real data I have 16 different dataframes, so if possible the code should allow to put 16 rows from 16 dataframes in another one, that will be created.

Answer

Assuming that your columns are always identical, you can do the following with dplyr and purrr packages:

library(purrr)
library(dplyr)

df1 = data.frame(Industries = c("c1", "c2", "c3", "c4", "c5"), Exports = c(100, 40, 30, 10, 50), Imports =c(90,50,25,15,50))
df2 = data.frame(Industries = c("c1", "c2", "c3", "c4", "c5"), Exports = c(20, 90, 10, 30, 60), Imports =c(40,30,25,55,40))

list(df1, df2) %>% map_df(~ filter(., Industries == "c3"))
#>   Industries Exports Imports
#> 1         c3      30      25
#> 2         c3      10      25
  • list(df1, df2) is combining your data frames into a list
  • map_df iterates on each, promising (if possible) to return results as a data frame.
  • ~ filter(., Industries == "c3") is the function run on each data frame, which returns only the rows where Industries == "c3".
Comments