Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using dataframe column to specify dataframes for bind_rows in r

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading