Arindam Arindam - 16 days ago 7
R Question

Combining columns from different files into a single column in a new file in R

I have extracted chosen columns from multiple files into new as many data sets as files. Now I need to rbind all of them into a single column in a new file.

I am using below command

comments <- bind_rows(data1,data2,data3,data4,data5,data6,data7)


Each of the data set has a single column but colname is different and I want all of them in a single column in comments data set.

The output I get is comments dataset with 7 columns instead of 1, struggling to understand why. Pls help

Answer

We can change the column names all at once in a list and then apply bind_rows

library(dplyr)
lapply(mget(paste0("data", 1:7)), setNames, "Col1") %>% 
                     bind_rows()

Or use rbindlist from data.table which will give a single column

library(data.table)
rbindlist(mget(paste0("data", 1:7))