SssssssAaaaaaa
SssssssAaaaaaa

Reputation: 101

A Function to Merge 100 Dataframes to one Dataframe

I am new to programming and R is my first programming language to learn.

I want to merge 100 dataframes; each dataframe contains one column and 20 observations, as shown below:

df1 <- as.data.frame(c(6,3,4,4,5,...))
df2 <- as.data.frame(c(2,2,3,5,10,...))
df3 <- as.data.frame(c(5,9,2,3,7,...))
...
df100 <- as.data.frame(c(4,10,5,9,8,...))

I tried using df.list <- list(df1:df100) to construct an overall dataframe for all of the dataframes but I am not sure if df.list merges all the columns from all the dataframes together in a table.

Can anyone tell me if I am right? And what do I need to do?

Upvotes: 2

Views: 303

Answers (2)

Anoushiravan R
Anoushiravan R

Reputation: 21908

We can also use reduce function from purrr package, after creating a character vector of names of data frames:

library(dplyr)
library(purrr)

names <- paste0("df", 1:100)

names %>% 
  reduce(.init = get(names[1]), ~ bind_rows(..1, get(..2)))

Or in base R:

Reduce(function(x, y) rbind(x, get(y)), names, init = get(names[1]))

Upvotes: 3

akrun
akrun

Reputation: 886938

We can use mget to get all the objects into a list by specifying the pattern in 'ls' to check for object names that starts (^) with 'df' followed by one or mor digits (\\d+) till the end ($) of the string

df.list <- mget(ls(pattern = '^df\\d+$'))

From the list, if we can want to cbind all the datasets, use cbind in do.call

out <- do.call(cbind, df.list)

NOTE: It is better not to create multiple objects in the global environment. We could have read all the data into a list directly or constructed within a list i.e. if the files are read from .csv, get all the files with .csv from the directory of interest with list.files, then loop over the files in lapply, read them individually with read.csv and cbind

files <- list.files(path = 'path/to/your/location', 
         pattern = '\\.csv$', full.names = TRUE)
out <- do.call(cbind, lapply(files, read.csv))

Upvotes: 3

Related Questions