I have a dataframe (here, dfToc) containing a list of dataframe names. I would like to use it to specify other dataframes to concatenate via the tidyverse command bind_rows. The concatenation works if I explicitly name the other dataframes in the bind_rows command, but not if I use dfToc to specify the other dataframes. It seems elementary but I am stumped. A simplified example follows.
library(tidyverse)
df1 <- data.frame(Name = c("Jon", "Bill", "Maria", "Ben", "Tina"),
Score = c(23, 41, 32, 58, 26))
df2 <- data.frame(Name = c("Jon", "Bill", "Maria", "Ben", "Tina"),
Score = c(32, 14, 23, 85, 62))
dfToc <- data.frame(fn = c('df1' , 'df2'))
dfToc$fn
#> [1] "df1" "df2"
# explicitly naming the dataframes works
bind_rows(list(df1 , df2))
#> Name Score
#> 1 Jon 23
#> 2 Bill 41
#> 3 Maria 32
#> 4 Ben 58
#> 5 Tina 26
#> 6 Jon 32
#> 7 Bill 14
#> 8 Maria 23
#> 9 Ben 85
#> 10 Tina 62
# using dfToc to specify the dataframes results in an error
bind_rows(list(dfToc$fn))
#> Error in `bind_rows()`:
#> ! Argument 1 must be a data frame or a named atomic vector.
#> Backtrace:
#> â–†
#> 1. └─dplyr::bind_rows(list(dfToc$fn))
#> 2. └─rlang::abort(glue("Argument {i} must be a data frame or a named atomic vector."))
Thanks for any help!
>Solution :
dfToc$fn is a character vector representing the names of your data frames. It is not a list of data frames, which is what bind_rows needs. To get multiple objects from your workspace into a list using the names of those objects, we can use mget:
bind_rows(mget(dfToc$fn))
#> Name Score
#> 1 Jon 23
#> 2 Bill 41
#> 3 Maria 32
#> 4 Ben 58
#> 5 Tina 26
#> 6 Jon 32
#> 7 Bill 14
#> 8 Maria 23
#> 9 Ben 85
#> 10 Tina 62