【问题标题】:Change column names of data frames stored in a list by condition按条件更改存储在列表中的数据框的列名
【发布时间】: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 %&gt;% map(rename, abundance = abund) 的列表可以正常工作,但有更多 dfs 和不同的列名,它会说:

错误:无法重命名不存在的列。 x 列abund 不存在。

我尝试了几个代码:

lst %>% set_names(~sub("abund", "abundance", names(.x)))
lst %>% set_names(~sub("abund", "abundance", .x))

还有许多其他人使用map_ifmap_atrename_ifrename_at 等,但没有任何效果。

【问题讨论】:

  • 您的样本数据中有很多错误,包括:C 而不是c;未关闭rep(.);未关闭data.frame(.)。在完成问题之前,在新的 R 实例中尝试自己的代码会有所帮助。

标签: r list tidyverse rename columnname


【解决方案1】:

dplyr::rename_with() 对每个列名应用一个函数。在该函数中,我们可以使用grepl() 检查名称是否包含“bund”或“individuals”,然后这些列被重命名。从技术上讲,不包含我们正在寻找的字符串的列也会被重命名,但它们会再次获得旧名称,因此那里没有任何更改。

library(dplyr)
library(purrr)

map(lst, ~ rename_with(., ~ ifelse(
  grepl("abund|individuals", .), "abundance", .
)))
#> $spiders
#>   plot abundance habitat
#> 1    1         1  forest
#> 2    2         4  forest
#> 3    3         8  forest
#> 
#> $bugs
#>   plot abundance
#> 1    1         1
#> 2    2         4
#> 3    3         8
#> 
#> $birds
#>   plot abundance habitat
#> 1    1         1  forest
#> 2    2         4  forest
#> 3    3         8  forest
#> 4    1         1  visual
#> 5    2         4  visual
#> 6    3         8  visual

我们可以使用新的,而不是使用 tidyverse 风格的匿名函数 base R 匿名函数样式,以使代码更易于理解。

map(lst, \(df) rename_with(df, \(name) ifelse(
  grepl("abund|individuals", name), "abundance", name
)))
#> $spiders
#>   plot abundance habitat
#> 1    1         1  forest
#> 2    2         4  forest
#> 3    3         8  forest
#> 
#> $bugs
#>   plot abundance
#> 1    1         1
#> 2    2         4
#> 3    3         8
#> 
#> $birds
#>   plot abundance habitat
#> 1    1         1  forest
#> 2    2         4  forest
#> 3    3         8  forest
#> 4    1         1  visual
#> 5    2         4  visual
#> 6    3         8  visual

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-23
    • 2020-02-18
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2016-02-07
    • 2020-06-09
    相关资源
    最近更新 更多