R name colnames and rownames in list of data.frames with lapply

混江龙づ霸主 提交于 2019-11-29 05:14:22

You need to remember that the object x inside the lapply is not the original object, but a copy. Changing the colnames of the copy does not impact the original object. You need to return x in order to get a new copy of the object that includes the new names.

new_obj = lapply(a, function(x) {
   colnames(x) <- paste("col",1:10,sep="")
   return(x)
  })

I'll prefer setNames in this case

set.seed(1)
datalist <- list(dat1 = data.frame(A = 1:10, B = rnorm(10)),
                 dat2 = data.frame(C = 100:109, D = rnorm(10))
                 )
lapply(datalist, names)
##  $dat1
## [1] "A" "B"

## $dat2
## [1] "C" "D"

datalist <- lapply(datalist, setNames, paste0("col", 1:2))
lapply(datalist, names)
## $dat1
## [1] "col1" "col2"

## $dat2
## [1] "col1" "col2"

EDIT

A more general solution to modify rownames and colnames within a list

lapply(datalist, "colnames<-", paste0("col", 1:2))
lapply(datalist, "rownames<-", letters[1:10])
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!