如何按条件批量重命名R列表中存储的多个data frame的列名
问题原因
原来的rename语法要求指定的旧列名必须存在于当前数据框中,你的列表里不同数据框的丰度列命名不一致,部分数据框不存在你指定的abund/individuals列,所以触发报错。
解决方案
tidyverse 写法(适配你用到的purrr/dplyr语法)
用rename_with配合any_of匹配列,any_of只会选择当前数据框中真实存在的列,不存在的列会自动跳过,不会触发报错:
library(tidyverse) lst_renamed <- lst %>% map(function(df) { df %>% # 把存在的abund、individuals列统一改名为abundance rename_with(~"abundance", .cols = any_of(c("abund", "individuals"))) })
验证结果
运行map(lst_renamed, colnames)可以看到所有数据框的丰度列都已统一为abundance:
$spiders [1] "plot" "abundance" "habitat" $bugs [1] "plot" "abundance" $birds [1] "plot" "abundance" "habitat" "method"
base R 写法
不需要加载第三方包也可以实现:
lst_renamed_base <- lapply(lst, function(df) { target_col <- names(df) %in% c("abund", "individuals") names(df)[target_col] <- "abundance" return(df) })
内容的提问来源于stack exchange,提问作者Tobias Richter
相关产品推荐
相关产品推荐

