I have several dataframes:
toto1_1 <- data.frame(x=1:3)
toto1_2 <- data.frame(x=1:3)
titi1_1 <- data.frame(x=1:3)
titi1_2 <- data.frame(x=1:3)
What is the best way to concatenate these tables using 2 different patterns?
Thank you.
I have several dataframes:
toto1_1 <- data.frame(x=1:3)
toto1_2 <- data.frame(x=1:3)
titi1_1 <- data.frame(x=1:3)
titi1_2 <- data.frame(x=1:3)
What is the best way to concatenate these tables using 2 different patterns?
Thank you.
The mget
function will return a list of data-objects when given a character vector:
totoList <- mget( paste0( rep(c("toto","titi"),each=2), rep(c("1_1","1_2") ) )
str(totoList)
List of 4
$ toto1_1:'data.frame': 3 obs. of 1 variable:
..$ x: int [1:3] 1 2 3
$ toto1_2:'data.frame': 3 obs. of 1 variable:
..$ x: int [1:3] 1 2 3
$ titi1_1:'data.frame': 3 obs. of 1 variable:
..$ x: int [1:3] 1 2 3
$ titi1_2:'data.frame': 3 obs. of 1 variable:
..$ x: int [1:3] 1 2 3
If the goal were as single lust, then that could be an intermediate result on the way to:
do.call( "rbind", totoList) # rbind transforms character value to an R function
x
toto1_1.1 1
toto1_1.2 2
toto1_1.3 3
toto1_2.1 1
toto1_2.2 2
toto1_2.3 3
titi1_1.1 1
titi1_1.2 2
titi1_1.3 3
titi1_2.1 1
titi1_2.2 2
titi1_2.3 3
please see some suggestions below. 1. They're concatenated using the rbind() function 2. They're concatenated using the c() function -- retains as separate vector elements but concatenated into a single element 3. Perhaps more useful because it preserves the table names of the original tables for future analysis and sorting: to add each into a list, then to create a data.frame for each table name and it's data; and then concatenate into a single object using rbind()
toto1_1 <- data.frame(x=1:3)
toto1_2 <- data.frame(x=1:3)
titi1_1 <- data.frame(x=1:3)
titi1_2 <- data.frame(x=1:3)
#1
rbind(toto1_1,toto1_2,titi1_1,titi1_2)
#2
c(toto1_1,toto1_2,titi1_1,titi1_2)
#3
l <- list(toto1_1=toto1_1,toto1_2=toto1_2,titi1_1=titi1_1,titi1_2=titi1_2)
do.call(rbind,lapply(names(l),FUN=function(x) { data.frame(table_name=x,table_data=l[[x]]) }))