user6644063 user6644063 - 2 months ago 5x
R Question

list - rename specific data.frames column with lapply

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.


You need to use {} and return x:

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


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

As a reproducible example, you could use

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