Using lapply to change column names of data frame list

I am trying to use lapply in a list of data frames; but unable to pass parameters correctly (I think).

List of data frames:

df1 <- data.frame(A = 1:10, B= 11:20) df2 <- data.frame(A = 21:30, B = 31:40) listDF <- list(df1, df2,df3) #multiple data frames w. way less columns than the length of vector todos 

Vector with column names:

 todos <-c('col1','col2', ......'colN') 

I want to change the column names using lapply:

 lapply (listDF, function(x) { colnames(x)[2:length(x)] <-todos[1:length(x)-1] } ) 

but that doesn't change the names at all. I do not transmit the data frames myself, but something else? I just want to change the names, and not return the result to a new object.

Thanks in advance, p.

+5
source share
2 answers

You can also use setNames if you want to replace all columns

 df1 <- data.frame(A = 1:10, B= 11:20) df2 <- data.frame(A = 21:30, B = 31:40) listDF <- list(df1, df2) new_col_name <- c("C", "D") lapply(listDF, setNames, nm = new_col_name) ## [[1]] ## CD ## 1 1 11 ## 2 2 12 ## 3 3 13 ## 4 4 14 ## 5 5 15 ## 6 6 16 ## 7 7 17 ## 8 8 18 ## 9 9 19 ## 10 10 20 ## [[2]] ## CD ## 1 21 31 ## 2 22 32 ## 3 23 33 ## 4 24 34 ## 5 25 35 ## 6 26 36 ## 7 27 37 ## 8 28 38 ## 9 29 39 ## 10 30 40 

If you need to replace only a subset of column names, you can use @Jogo's solution

 lapply(listDF, function(df) { names(df)[-1] <- new_col_name[-ncol(df)] df }) 

Last point, in R there is a difference between a: b - 1 and a: (b - 1)

 1:10 - 1 ## [1] 0 1 2 3 4 5 6 7 8 9 1:(10 - 1) ## [1] 1 2 3 4 5 6 7 8 9 

EDIT

If you want to change the column names of data.frame in a global environment from a list, you can use list2env , but I'm not sure if this is the best way to achieve what you want. You also need to change your list and use a named list, the name must match the name data.frame , which you need to replace.

 listDF <- list(df1 = df1, df2 = df2) new_col_name <- c("C", "D") listDF <- lapply(listDF, function(df) { names(df)[-1] <- new_col_name[-ncol(df)] df }) list2env(listDF, envir = .GlobalEnv) str(df1) ## 'data.frame': 10 obs. of 2 variables: ## $ A: int 1 2 3 4 5 6 7 8 9 10 ## $ C: int 11 12 13 14 15 16 17 18 19 20 
+11
source

try the following:

 lapply (listDF, function(x) { names(x)[-1] <- todos[-length(x)] x }) 

You will get a new list with modified data frames. If you want to manipulate listDF directly:

 for (i in 1:length(listDF)) names(listDF[[i]])[-1] <- todos[-length(listDF[[i]])] 
+1
source

Source: https://habr.com/ru/post/1235365/


All Articles