首页 > 解决方案 > 如何使用 mutate() 在所有其他列的函数中创建一个新列而不命名它们

问题描述

我有一个tibble(我已经在使用tidyverse),但由于它很大,让我们使用稍微修改的iris数据集:

iris %>%
  as_tibble() %>%
  select(-5) 

我想创建另一列,它是这些列的平方和的平方根(dbl您可能会注意到,它们都是 )。但是,这种方法应该对任意数量的列和任意名称进行泛化,不仅因为原始数据集有更多列,还因为它更优雅。

此代码有效,但特定于具有以下名称的这些列:

iris %>%
  as_tibble() %>%
  select(-5) %>%
  mutate(linear = sqrt(Sepal.Length^2+Sepal.Width^2+Petal.Length^2+Petal.Width^2)) %>%
  arrange(linear)

这给出了预期的输出:

> iris %>%
+   as_tibble() %>%
+   select(-5) %>%
+   mutate(linear = sqrt(Sepal.Length^2+Sepal.Width^2+Petal.Length^2+Petal.Width^2)) %>%
+   arrange(linear)
# A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width linear
          <dbl>       <dbl>        <dbl>       <dbl>  <dbl>
 1          4.5         2.3          1.3         0.3   5.23
 2          4.3         3            1.1         0.1   5.36
 3          4.4         2.9          1.4         0.2   5.46
 4          4.4         3            1.3         0.2   5.49
 5          4.4         3.2          1.3         0.2   5.60
 6          4.6         3.1          1.5         0.2   5.75
 7          4.6         3.2          1.4         0.2   5.78
 8          4.8         3            1.4         0.1   5.83
 9          4.7         3.2          1.3         0.2   5.84
10          4.8         3            1.4         0.3   5.84
# … with 140 more rows

标签: rdplyr

解决方案


您还可以使用此解决方案:

library(dplyr)
library(purrr)

iris %>%
  as_tibble() %>%
  select(-5) %>%
  mutate(linear = pmap(., ~ sqrt(sum(c(...) ^ 2)))) %>%
  unnest(linear) %>%
  arrange(linear)

# A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width linear
          <dbl>       <dbl>        <dbl>       <dbl>  <dbl>
 1          4.5         2.3          1.3         0.3   5.23
 2          4.3         3            1.1         0.1   5.36
 3          4.4         2.9          1.4         0.2   5.46
 4          4.4         3            1.3         0.2   5.49
 5          4.4         3.2          1.3         0.2   5.60
 6          4.6         3.1          1.5         0.2   5.75
 7          4.6         3.2          1.4         0.2   5.78
 8          4.8         3            1.4         0.1   5.83
 9          4.7         3.2          1.3         0.2   5.84
10          4.8         3            1.4         0.3   5.84
# ... with 140 more rows

如果您想知道如何将purrr函数应用于此类问题,请查看亲爱的 akrun 提供综合答案。


推荐阅读