Rename Columns of Data.frame in list

前端 未结 1 1875
梦谈多话
梦谈多话 2020-12-09 22:12

I am trying to use lapply (and want the solution with lapply) to rename columns of a data.frame located in a list, but it\'s returning names, not the renamed data.frames:

相关标签:
1条回答
  • 2020-12-09 22:25

    We may need to return the object after naming it.

     li_2 <- lapply(seq_along(li), function(i) {
                   colnames(li[[i]]) <- names(li)[i]
                   li[[i]]})
    

    Or this can be done with setNames

     li_2 <- lapply(names(li), function(x) setNames(li[[x]], x) )
    

    Or we could use Map, which is a wrapper for mapply (that is a multivariate version of sapply). We apply the FUN to corresponding elements of each input.

     li_2 <- Map(setNames, li, names(li))
    

    Here, we are changing the column names of each list element with corresponding names of the list element. If we are using anonymous function, it would be

     Map(function(x,y) setNames(x,y), li, names(li))
    
    0 讨论(0)
提交回复
热议问题