Tob*_*ter 1 r rename list tidyverse r-colnames
我有一个包含不同分类群的几个数据框的列表。不同分类单元的 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
Run Code Online (Sandbox Code Playgroud)
在我的原始列表中,我有更多的 dfs.. 我想做的是迭代 dfs 并将所有带有“abund”或“individuals”的 colname 更改为“abundance”(如果还没有的话)。
如果我有一个只有一个 df 的列表,lst %>% map(rename, abundance = abund)效果很好,但有更多 dfs 和不同的 colnames,它会说:
错误:无法重命名不存在的列。x 列
abund不存在。
我尝试了几个代码:
lst %>% set_names(~sub("abund", "abundance", names(.x)))
lst %>% set_names(~sub("abund", "abundance", .x))
Run Code Online (Sandbox Code Playgroud)
还有许多其他的map_if,,,,等等map_at,但没有任何效果。rename_ifrename_at
dplyr::rename_with()将函数应用于每个列名。在该函数中,我们可以检查名称是否包含 \xe2\x80\x9cabund\xe2\x80\x9d 或 \xe2\x80\x9cindividuals\xe2\x80\x9d grepl(),然后这些列被重命名。don\xe2\x80\x99t 包含我们在技术上查找的字符串的列也会被重命名,但它们再次收到旧名称,因此那里没有任何更改。
library(dplyr)\nlibrary(purrr)\n\nmap(lst, ~ rename_with(., ~ ifelse(\n grepl("abund|individuals", .), "abundance", .\n)))\n#> $spiders\n#> plot abundance habitat\n#> 1 1 1 forest\n#> 2 2 4 forest\n#> 3 3 8 forest\n#> \n#> $bugs\n#> plot abundance\n#> 1 1 1\n#> 2 2 4\n#> 3 3 8\n#> \n#> $birds\n#> plot abundance habitat\n#> 1 1 1 forest\n#> 2 2 4 forest\n#> 3 3 8 forest\n#> 4 1 1 visual\n#> 5 2 4 visual\n#> 6 3 8 visual\nRun Code Online (Sandbox Code Playgroud)\n我们可以使用新的\nbase R 匿名函数样式,而不是使用 tidyverse 样式的匿名函数,以使代码更容易理解。
\nmap(lst, \\(df) rename_with(df, \\(name) ifelse(\n grepl("abund|individuals", name), "abundance", name\n)))\n#> $spiders\n#> plot abundance habitat\n#> 1 1 1 forest\n#> 2 2 4 forest\n#> 3 3 8 forest\n#> \n#> $bugs\n#> plot abundance\n#> 1 1 1\n#> 2 2 4\n#> 3 3 8\n#> \n#> $birds\n#> plot abundance habitat\n#> 1 1 1 forest\n#> 2 2 4 forest\n#> 3 3 8 forest\n#> 4 1 1 visual\n#> 5 2 4 visual\n#> 6 3 8 visual\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1022 次 |
| 最近记录: |