Home > Net >  How to combine two datatables by position (not by rownames nor by colnames)?
How to combine two datatables by position (not by rownames nor by colnames)?

Time:03-12

I wanted to combine two data tables, where one of them has the information of the other in a tidy format. One example of what I wanted would be to merge two tables like this ones:

information <- data.frame(c("standard-1", "standard-2", "standard-3"), c("sample-1", "sample-2", "sample-3"))
data <- data.frame(c(2, 4, 5), c(4, 2, 6))

And obtain a new data table where each column would came from a table and each row will be an observation. Like the one created with this code:

all_data <- data.frame(c("standard-1", "standard-2", "standard-3", "sample-1", "sample-2", "sample-3"), c(2, 4, 5, 4, 2, 6))

I have tried in a very low elegant way by applying one loop that goes for each column of each table and adding the information to a new table, but I always receive errors about the information having different names (I don't care about columns or rows names) or having different sizes

Any help would be appreciated

CodePudding user response:

You can unlist both the dataframes in a vector to get the resultant dataframe.

result <- data.frame(info_col = unlist(information), 
                     data_col = unlist(data), row.names = NULL)
result

#    info_col data_col
#1 standard-1        2
#2 standard-2        4
#3 standard-3        5
#4   sample-1        4
#5   sample-2        2
#6   sample-3        6

This would work considering both the dataframes are of equal dimensions and have the same length when unlisted in a vector.

  • Related