【发布时间】:2021-11-10 16:27:47
【问题描述】:
我有一个包含不同分类群的几个数据框的列表。不同分类群的 df 具有不同的长度,并且对于具有“相同信息”的列具有不同的名称,例如“丰富”、“丰富”、“个人”。我给你举个例子:
spiders <- data.frame(plot = c(1,2,3),
abundance = c(1,4,8),
habitat = c(rep("forest", 3)))
bugs <- data.frame(plot = c(1,2,3),
abund = c(1,4,8))
birds<- data.frame(plot = c(1,2,3),
individuals= C(1,4,8),
habitat = c(rep("forest", 3)),
method = c(rep("visual", 3)))
lst <- list("spiders" = spiders, "bugs" = bugs, "birds" = birds)
show(lst)
$spiders
plot abundance habitat
1 1 1 forest
2 2 4 forest
3 3 8 forest
$bugs
plot abund
1 1 1
2 2 4
3 3 8
$birds
plot individuals habitat method
1 1 1 forest visual
2 2 4 forest visual
3 3 8 forest visual
在我的原始列表中,我有更多的 dfs。我想要做的是遍历 dfs,并将所有带有“abund”或“individuals”的 colnames 更改为“abundance”,如果还没有的话。
如果我有一个只有一个 df lst %>% map(rename, abundance = abund) 的列表可以正常工作,但有更多 dfs 和不同的列名,它会说:
错误:无法重命名不存在的列。 x 列
abund不存在。
我尝试了几个代码:
lst %>% set_names(~sub("abund", "abundance", names(.x)))
lst %>% set_names(~sub("abund", "abundance", .x))
还有许多其他人使用map_if、map_at、rename_if、rename_at 等,但没有任何效果。
【问题讨论】:
-
您的样本数据中有很多错误,包括:
C而不是c;未关闭rep(.);未关闭data.frame(.)。在完成问题之前,在新的 R 实例中尝试自己的代码会有所帮助。
标签: r list tidyverse rename columnname