Rename Columns of Data.frame in list

半世苍凉 提交于 2019-11-28 10:23:36

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))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!