在 R 中使用 nest() 和 map() 后重命名多个列的最佳方法

Best way to rename multiple columns after using nest() and map() in R

提问人:TheBoomerang 提问时间:10/10/2022 更新时间:10/10/2022 访问量:82

问:

我想知道使用 nest() 和 map() 后重命名多个列的最佳方法是什么。

我有一个示例代码,说明我目前使用虹膜数据集为实现这一目标所做的工作。


iris_names <- colnames(iris[, 1:4])

iris_sqrt <- iris %>% 
  nest(-Species) %>% 
  mutate(square_root = map(data, sqrt)) %>% 
  unnest(square_root)

names(iris_sqrt)[3:ncol(iris_sqrt)] <- paste0(iris_names, ".sd")

在这里,我在创建 iris_sqrt 之前制作一个要重命名的列名的向量,然后使用 paste0 重命名。此方法的缺点是列名必须以与iris_names向量相同的顺序出现才能正确重命名。

有没有一种 tidyverse/dplyr 方法可以做到这一点?

loops 字典 dplyr 重命名 nest

评论


答:

1赞 Maël 10/10/2022 #1

您可以在通话中使用。使用 on 、 apply 、 使用参数可以更改新列的名称,并使用 用于删除计算期间使用的列:mutatemapacrosseverythingsqrt.names.keep = "unused"mutate

iris %>% 
  nest(data = -Species) %>% 
  mutate(square_root = map(data, ~ .x %>% 
                             mutate(across(everything(), sqrt, 
                                           .names = "{.col}.sd"),
                                           .keep = "unused"))) %>% 
  unnest(square_root)

输出

# A tibble: 150 × 6
   Species data              Sepal.Length.sd Sepal.Width.sd Petal.Length.sd Petal.Width.sd
   <fct>   <list>                      <dbl>          <dbl>           <dbl>          <dbl>
 1 setosa  <tibble [50 × 4]>            2.26           1.87            1.18          0.447
 2 setosa  <tibble [50 × 4]>            2.21           1.73            1.18          0.447
 3 setosa  <tibble [50 × 4]>            2.17           1.79            1.14          0.447
 4 setosa  <tibble [50 × 4]>            2.14           1.76            1.22          0.447
 5 setosa  <tibble [50 × 4]>            2.24           1.90            1.18          0.447
 6 setosa  <tibble [50 × 4]>            2.32           1.97            1.30          0.632
 7 setosa  <tibble [50 × 4]>            2.14           1.84            1.18          0.548
 8 setosa  <tibble [50 × 4]>            2.24           1.84            1.22          0.447
 9 setosa  <tibble [50 × 4]>            2.10           1.70            1.18          0.447
10 setosa  <tibble [50 × 4]>            2.21           1.76            1.22          0.316
# … with 140 more rows
# ℹ Use `print(n = ...)` to see more rows

评论

1赞 TheBoomerang 10/10/2022
谢谢 - 效果很好,看起来很简单!