Question

I have some tables Table1,Table2,Table3,Table4. They have the same number of columns and rows and what I want is to merge them into one big Table.

I have tried making a list of the tables and then converting it to a matrix but the output doesn't seem what I want.

l <- list(Table1, Table2, Table3, Table4)
l <- lapply(l, as.data.frame)
m <- matrix(unlist(l), nrow = length(l))

I have also tried to just merge the four tables using merge(Table1, Table2, Table3, Table4) but I am not sure about providing the proper arguments and therefore I get an error.

Error in fix.by(by.x, x) :
'by' must specify one or more columns as numbers, names or logical
Calls: merge -> merge.data.frame -> fix.by

I have also tried to write the tables to an external .txt file and then read from that file a new table.

#write.table(Table1, file = "file.txt", append = TRUE)
#write.table(Table2, file = "file.txt", append = TRUE, col.names=FALSE)
#write.table(Table3, file = "file.txt", append = TRUE, col.names=FALSE)
#write.table(Table4, file = "file.txt", append = TRUE, col.names=FALSE)

However this solution is inadequate for various reasons and I had to drop it.

By the way I would prefer the first solution to somehow work.

Edit: I forgot to mention that all four tables have identical indexes 1,2,3,.., and same columns names, etc. I am pointing this out because for example cbind doesn't fit well.

I am pretty sure this is a trivial task but I am stuck. Any help?

Was it helpful?

Solution

It is still a problem of different headings. This should do the trick:

names(table2) <- names(table1)
names(table3) <- names(table1)
names(table4) <- names(table1)

Do this for every table and then

rbind(table1,table2,...)

If you want to know if the headings are the same, you could compare them

names(table1) == names(table2)

etc.

OTHER TIPS

You are looking for rbind

try

do.call(rbind, list(Table1, Table2, Table3, Table4))

rbind should work if all your columns are the same in all tables. Follow Chinmay's answer. cbind is for concatenating data on columns. Else use sqldf.

library(sqldf)
m <- sqldf("select * from table1 union all select * from table2 union all 
             select * from table3 union all select * from table4")

Use union all if you want all your observations. Use union if you want to remove the duplicates. But this might be slower than rbind if your data sets are large.

you can use Reduce with merge :

l <- list(Table1, Table2, Table3, Table4)
Reduce(function(x, y) merge(x, y, all=TRUE), l)

hth

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top