【发布时间】:2021-04-07 15:50:53
【问题描述】:
我有一个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
【问题讨论】: