Search code examples
rloopsrbind

Combine loop with Rbind


I'm trying to do a loop that appends through dataframes. I don't know how to call the dataframes in the loop when I use rbind. I tried with paste0 but didn't work. Here is a reproducible example:

library(metRology)

x <- c(1,2,3)
y <- c(1,2,3)

df_a_1 <- data.frame(x,y)
df_a_2 <- data.frame(x,y)

df_b_1 <- data.frame(x,y)
df_b_2 <- data.frame(x,y)

df_c_1 <- data.frame(x,y)
df_c_2 <- data.frame(x,y)

letters <- c("a", "b", "c")

#Loop
for (i in letters) {
  df_i <- rbind(paste0("df_", i "_1"), paste0("df", i, "_2"))
}

Thanks in advance!


Solution

  • You can get and assign variables by their names assuming your data frames are stored in the R global environment:

    library(tidyverse)
    
    x <- c(1,2,3)
    y <- c(1,2,3)
    
    df_a_1 <- data.frame(x,y)
    df_a_2 <- data.frame(x,y)
    
    df_b_1 <- data.frame(x,y)
    df_b_2 <- data.frame(x,y)
    
    df_c_1 <- data.frame(x,y)
    df_c_2 <- data.frame(x,y)
    
    letters <- c("a", "b", "c")
    
    for(l in letters) {
      prefix <- str_glue("df_{l}")
      res <- names(globalenv()) %>%
             keep(~ .x %>% str_detect(prefix)) %>%
             map(get) %>%
             reduce(rbind)
      assign(prefix, res)
    }
    
    df_a
    #>   x y
    #> 1 1 1
    #> 2 2 2
    #> 3 3 3
    #> 4 1 1
    #> 5 2 2
    #> 6 3 3
    df_b
    #>   x y
    #> 1 1 1
    #> 2 2 2
    #> 3 3 3
    #> 4 1 1
    #> 5 2 2
    #> 6 3 3
    

    Created on 2021-11-10 by the reprex package (v2.0.1)