Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rbind data frames based on a common pattern in data frame name

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.

like image 217
Jojo Avatar asked Jan 23 '17 17:01

Jojo


People also ask

How do you Rbind two data frames?

To join two data frames (datasets) vertically, use the rbind function. The two data frames must have the same variables, but they do not have to be in the same order. If data frameA has variables that data frameB does not, then either: Delete the extra variables in data frameA or.

What is the meaning of the Rbind ()?

The rbind() function represents a row bind function for vectors, data frames, and matrices to be arranged as rows. It is used to combine multiple data frames for data manipulation.

Does Rbind use column names?

For rbind column names are taken from the first argument with appropriate names: colnames for a matrix, or names for a vector of length the number of columns of the result.

What is the data frame name in R?

A data frame is a list of variables of the same number of rows with unique row names, given class "data. frame" . If no variables are included, the row names determine the number of rows. The column names should be non-empty, and attempts to use empty names will have unsupported results.


2 Answers

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+")))
like image 145
akrun Avatar answered Sep 22 '22 01:09

akrun


You can try:

new_df <- do.call("rbind",mget(ls(pattern = "^df.*")))
like image 25
InspectorSands Avatar answered Sep 25 '22 01:09

InspectorSands