8

Say I have multiple data frames which all have identical vector names and I'd like to cbind all which have a commmon pattern. So for these 3 data frames:

df.1 <- data.frame(column1 = factor(sample(c("Male","Female"), 10, replace=TRUE)),
                   speed=runif(10))
df.2 <- data.frame(column1 = factor(sample(c("Male","Female"), 10, replace=TRUE)),
                   speed=runif(10))
df.3 <- data.frame(column1 = factor(sample(c("Male","Female"), 10, replace=TRUE)),
                   speed = runif(10))

I would like to rbind everything with the common pattern "df.*"

I have tried creating a list and then creating a data-frame from this using:

temp <- lapply(ls(pattern = "df.*"), get) 
temp2<- as.data.frame(temp)

However this only produces a data frame of 6 columns effectively cbinding the whole thing rather than rbinding.

Jojo
  • 4,951
  • 7
  • 23
  • 27

2 Answers2

16

We can use ls with mget

library(data.table)
rbindlist(mget(ls(pattern = "^df\\.\\d+")))

Or with dplyr

library(dplyr)
mget(ls(pattern="^df\\.\\d+")) %>%
              bind_rows()

Or with rbind from base R

do.call(rbind, mget(ls(pattern="^df\\.\\d+")))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Perfect, thank you. Question: why use `"^df\\.\\d+"` rather than `"df.*"` ? – Jojo Jan 23 '17 at 17:17
  • @JojoOno Based on the objects you created, `df.1`, `df.2`, `df.3` etc, I thought the patterns would be very specific i.e. 'df' at the start (`^`) of the string, followed by `.` (which is a metacharacter meaning any character can be matched, so we escape (`\\` it), followed by one or more digits (`\\d+`). – akrun Jan 23 '17 at 17:19
  • So this avoids the possibility of attaching any other objects with `"df."` occurring anywhere in the global environment? – Jojo Jan 23 '17 at 17:22
  • @JojoOno Suppose if your object is `dfram` or `dfxyz` it won't pick it up – akrun Jan 23 '17 at 17:23
  • Ok, grand. Thank you for the clarification. – Jojo Jan 23 '17 at 17:30
  • How can you do that but you only want one column of each df? Like column #2 etc – SqueakyBeak Jun 28 '23 at 19:51
  • 1
    @SqueakyBeak You may do `mget(ls(pattern="^df\\.\\d+")) %>% purrr::map_dfr(~ .x %>% select(2))` – akrun Jun 29 '23 at 05:21
5

You can try:

new_df <- do.call("rbind",mget(ls(pattern = "^df.*")))
InspectorSands
  • 2,859
  • 1
  • 18
  • 33