Search code examples
rlistloopsdata-management

merge the list data based on rownames in a loop


I'm trying to merge the data in a list, but I found their lengths are not exactly the same. Some has length 65 while some has 66.

enter image description here

datalist_BAL is my list of the data and datalist_BAL_name is the name of the list. I tried to create another list BAL with the rowname and merge together based on the rowname into BAL_data. Below is my code.

BAL <-list()
BAL_data<-data.frame()
    
for(i in 1:length(datalist_BAL)){
dt<- t(datalist_BAL[[i]])
rownames(dt)<-t(datalist_BAL_name[[i]])
BAL[[i]] <- dt
if (i==1) {next()}
BAL_data<-merge(BAL[[i-1]],BAL[[i]],by = "row.names",all= TRUE)

}

I generated BAL_data successfully but it only contains two columns.

enter image description here

So I wonder how I can run a loop to merge all the data of the list. Thanks in advance!


Solution

  • this is how I would do it. I think the problem was that you were ony using 2 dataframe to merge, this is why you only had two columns. You might also consider changing the column names.

    datalist_BAL <- list(data.table(text=c('a', 'b'), merge_col=c('1', '2')), 
    data.table(text=c('c', 'd'), merge_col=c('1', '2')),
                     data.table(text=c('e', 'f'), merge_col=c('1', '2')))
    
    
    BAL <-list()
    BAL_data<-data.frame()
    
    for(i in 1:length(datalist_BAL)){
      dt<- datalist_BAL[[i]]
      if (i==1) {
      BAL_data <- dt
    next()}
    BAL_data<-merge(BAL_data,dt,by = "merge_col",all= TRUE)
    
    }
    

    This means that your code will change like this

    BAL <-list()
    BAL_data<-data.frame()
    
    for(i in 1:length(datalist_BAL)){
    dt<- t(datalist_BAL[[i]])
    rownames(dt)<-t(datalist_BAL_name[[i]])
    BAL[[i]] <- dt
    if (i==1) {
    BAL_data <- dt
    next()}
    BAL_data<-merge(BAL_data,BAL[[i]],by = "row.names",all= TRUE)
    
    }