list - rename specific data.frames column with lapply

会有一股神秘感。 提交于 2019-12-11 04:24:53

问题


I have got a list with 10 data.frames and I need to rename ONLY one column of each data.frame. The column to rename is the no. 7 and I think I can do the trick with lapply.

Here what I tried without success:

lst <- lapply(lst, function(x) colnames(x)[7] <- 'new_name') 

I think I am really close to the solution but obviously I am missing something. Thanks


回答1:


You need to use {} and return x:

lst <- lapply(lst, function(x) {colnames(x)[7] <- 'new_name'; x}) 

Or

lst <- lapply(lst, function(x) {
  colnames(x)[7] <- 'new_name'
  x      
})

As a reproducible example, you could use

lapply(list(iris, iris), function(x) {colnames(x)[3] <- "test"; x})


来源:https://stackoverflow.com/questions/38826565/list-rename-specific-data-frames-column-with-lapply

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