R 如何根据条件更改列表中多个数据帧中列的名称?

R 如何根据条件更改列表中多个数据帧中列的名称?,r,dataframe,R,Dataframe,我有一个包含13个数据帧的列表。这些dfs具有不同的列数,有时具有不同的列标题。我需要的每个df中都有6列,我需要它们都有相同的名称,如图所示 header_cols <- c( "tribal_name", "st_usps_cd", "scc", "description", "total_emissions", "uom" ) 尽管如此,这可能会有问题,因为将来会添加更多的dfs,它们的名称可能不会出现在映射文件中。我考虑过使用这样的ifelse语句: if ( "polluta

我有一个包含13个数据帧的列表。这些dfs具有不同的列数,有时具有不同的列标题。我需要的每个df中都有6列,我需要它们都有相同的名称,如图所示

 header_cols <- c( "tribal_name", "st_usps_cd", "scc", "description", "total_emissions", "uom" )
尽管如此,这可能会有问题,因为将来会添加更多的dfs,它们的名称可能不会出现在映射文件中。我考虑过使用这样的ifelse语句:

if ( "pollutant_desc" %in% colnames() ) {
      rename( description = pollutant_desc )
    }

但是我不确定如何为列表中的多个数据帧格式化,以及当有多个不同的头名称时。有什么建议吗?

如果您想要的所有6列都出现在所有数据帧中,那么查找方法对我来说听起来不错

下面是一个使用4列的示例

创建查找表和一些伪数据

lookup_table <- data.frame(orignal_col = c('col1', 'col2', 'col3', 'col4'), 
                 new_col = c( "tribal_name", "st_usps_cd", "scc", "description"))

df1 <- data.frame(a = 1:3, col1 = 1:3, col2 = 3:5, col3 = 4:6, col4 = 2:4)
df2 <- data.frame(a = 1:3, col1 = 1:3, b = 1:3,col2 = 3:5, col3 = 4:6, col4 = 2:4)
all_input <- list(df1, df2)

all_input
#[[1]]
#  a col1 col2 col3 col4
#1 1    1    3    4    2
#2 2    2    4    5    3
#3 3    3    5    6    4

#[[2]]
#  a col1 b col2 col3 col4
#1 1    1 1    3    4    2
#2 2    2 2    4    5    3
#3 3    3 3    5    6    4

请注意,这两个数据帧除了常见的4列之外,还有一些额外的列,但是名称仅为4列更改,其余的保持不变

这里有一个非常简单的方法:

data(mtcars)
df1 <- mtcars %>% filter(cyl == 4)
df2 <- mtcars %>% filter(cyl == 6)
df3 <- mtcars %>% filter(cyl == 8)
list <- list(df1, df2, df3)

list_names <- c("df1", "df2", "df3")
df_col_names <- paste0("col", 1:11)

names(list) <- list_names
list <- lapply(list, setNames, df_col_names)
数据(mtcars)
df1%过滤器(气缸==4)
df2%过滤器(气缸==6)
df3%过滤器(气缸==8)

列出好答案。我要补充的是,对于给定的数据帧,这需要从列名称中的
lookup\u table$orignal\u col
中的每个元素精确匹配1次才能正常工作,因此如果不满足该条件,则需要稍微修改答案。这几乎有效!当我这样做时,它会将列重命名为“1”,而不是我在
lookup\u table$new\u col
中设置的名称。实际上,当我使用示例数据帧时,它也会这样做。它不是用新名称替换匹配的列,而是用数字替换它们。修复此问题的建议?@MarideeWeber如果您没有R4.0.0,则需要在
data.frame
调用
lookup\u table
中添加
stringsAsFactors=FALSE
。试试
lookup_table@RonakShah,非常感谢!我使用的是R3.5.2,这就成功了。
lapply(all_input, function(x) {
   names(x)[match(lookup_table$orignal_col, names(x))] <- lookup_table$new_col
   x
})

#[[1]]
#  a tribal_name st_usps_cd scc description
#1 1           1          3   4           2
#2 2           2          4   5           3
#3 3           3          5   6           4

#[[2]]
#  a tribal_name b st_usps_cd scc description
#1 1           1 1          3   4           2
#2 2           2 2          4   5           3
#3 3           3 3          5   6           4
data(mtcars)
df1 <- mtcars %>% filter(cyl == 4)
df2 <- mtcars %>% filter(cyl == 6)
df3 <- mtcars %>% filter(cyl == 8)
list <- list(df1, df2, df3)

list_names <- c("df1", "df2", "df3")
df_col_names <- paste0("col", 1:11)

names(list) <- list_names
list <- lapply(list, setNames, df_col_names)