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.
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.
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.
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.
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.
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+")))
You can try:
new_df <- do.call("rbind",mget(ls(pattern = "^df.*")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With