r - 如何使用 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
解决方案
您还可以使用此解决方案:
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 提供的综合答案。
推荐阅读
- json - Firebase 实时数据库的正确/高效结构正在苦苦挣扎。在这种情况下,非规范化是否合适?
- r - 垂直展开 sankeyNetwork 图
- javascript - React Button Reset Filters 方法清除信息
- python - Python中的spark_tensorflow_distributor库时间问题
- sql - Sql 时求和大小写
- flutter - 使用 qrscan 和 flutter_facebook_auth 在 Flutter 应用程序中重复依赖项
- python - 如何将 Docx 转换为 HTML
- datetime - Java 8 本地日期时间
- javascript - 我的 CSS 在 React 项目中被 Bootstrap 覆盖
- java - PeerListListener 不工作?它表明没有使用 PeerListListener,但是在广播类中我使用了它??所以不知道哪里错了?