Home > Software engineering >  I have a list of data frames and a character vector. I want to rename the second column of each data
I have a list of data frames and a character vector. I want to rename the second column of each data

Time:10-13

I have a list of dataframes. Each of these dataframes has the same number of columns and rows, and has a similar data structure:

df.list <- list(data.frame1, data.frame2, data.frame3)

I have a vector of characters:

charvec <- c("a","b","c")

I want to replace the column name of the second column in each data frame by iterating through the above character vector. For example, the first data frame's second column should be "a". The second data frame's second column should be "b".

[[1]]
  col1 a
1    1    2
2    2    3

[[2]]
  col1 b
1    1    2
2    2    3

CodePudding user response:

A reproducible example:

charvec <- c("a","b","c")
df_list <- list(df1 = data.frame(x = seq_len(3), y = seq_len(3)), df2 = data.frame(x = seq_len(4), y = seq_len(4)), df3 = data.frame(x = seq_len(5), y = seq_len(5)))

for(i in seq_along(df_list)){
  names(df_list[[i]])[2] <- charvec[i]
}

> df_list
$df1
  x a
1 1 1
2 2 2
3 3 3

$df2
  x b
1 1 1
2 2 2
3 3 3
4 4 4

$df3
  x c
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

CodePudding user response:

Also can use map2 from purrr. Thanks to @ismirsehregal for example data.

library(purrr)

map2(
  df_list,
  charvec,
  \(x, y) {
    names(x)[2] <- y
    x
  }
)

Output

$df1
  x a
1 1 1
2 2 2
3 3 3

$df2
  x b
1 1 1
2 2 2
3 3 3
4 4 4

$df3
  x c
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
  •  Tags:  
  • r
  • Related