简体   繁体   English

循环遍历数据框列表并重命名 R 中的列名

[英]Loop over list of data frames and rename column names In R

I did like to loop over a list of dataframes that I have and rename the column names.我确实想遍历我拥有的数据框列表并重命名列名。 Here is a sample of dataframes,这是数据框的示例,

dput(df)
df1 <- structure(list(v1..x = c("Silva", "Brandon", "Mango"),
               t2.v = c("James","Jane", "Egg")),
          class = "data.frame", row.names = c(NA,  -3L))

dput(df2)
df2 <- structure(list(v1..x = c("Silva", "Brandon", "Mango"),
               t2.r = c("James","Jane", "Egg")),
          class = "data.frame", row.names = c(NA,  -3L))
dput(df3)
df3 <- structure(list(v1..x = c("Silva", "Brandon", "Mango"),
               t2.v = c("James","Jane", "Egg"),
               d3...c = c("James","Jane", "Egg")),
          class = "data.frame", row.names = c(NA,  -3L))

I would like to loop over the list of this dataframes and rename the columns.我想遍历这个数据框的列表并重命名这些列。 I have a list of columns I want to replace with, I did like to use setnames so that to skip absent columns incase it finds one in a dataframes.Here is what I tried but only changes first column我有一个要替换的列列表,我确实喜欢使用setnames以便跳过缺少的列,以防它在数据框中找到一个列。这是我尝试过的,但只更改了第一列

lst_df <- list(df1,df2,df3)
oldnames<- c('v1..x','t2.v','d3...c')
newnames <- c('v1','t2_v','d3')
lst <- lapply(lst_df, function(x) setNames(x, gsub(oldnames, newnames, names(x))) )

note columns in some dataframes might not be same length.Please help注意某些数据框中的列可能长度不同。请帮助

In this cases data.table may come in quite handy.在这种情况下, data.table可能会派上用场。 Its setnames function is more flexible than setNames .它的setnames function 比setNames更灵活。

library(data.table)
oldnames<- c('v1..x','t2.v','d3...c')
newnames <- c('v1','t2_v','d3')

# convert df-s to data.table
lapply(lst_df, setDT)
# setnames function from data.table is quite flexible
lapply(lst_df, setnames, oldnames, newnames, skip_absent = TRUE)

Have into account that this will only change exact matches.考虑到这只会改变完全匹配。 If you want to change those string patterns, the easiest thing will likely be to run a for and use a regex.如果您想更改这些字符串模式,最简单的方法可能是运行 for 并使用正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM