r - 'mutate' 在 R 中的 tidyverse 中添加两列,其中包含一个 fn 调用
问题描述
这是一个 R 版本 3.4.4 问题
一个投票函数voteOnBase
,接受 2 个参数并返回一个 2 元素列表: theWINNER
和 the VOTE.COUNT
。我想用它将这两列添加到notVotedYet
tibble。以下代码运行正确。
library(tidyverse)
withVotes <- notVotedYet %>%
group_by(BASE) %>%
mutate(WINNER = voteOnBase(BASE, CODES)[[1]],
VOTE.COUNT = voteOnBase(BASE, CODES)[[2]])
但是,它会voteOnBase
在相同的输入上调用两次。如何消除额外的函数调用但仍添加相同的两列?
解决方案
没有一些示例数据和输出就不容易回答,但我建议写voteOnBase()
返回一个小标题,而不是一个列表。然后,您可以将结果存储在列表列中并使用创建列unnest()
。
举例说明:这里有一个函数,square_it()
它和你的一样,接受 2 个参数并返回 2 个元素 - 但作为 tibble 中的列。
square_it <- function(x, y) {
tibble(x = x^2, y = y^2)
}
我们可以使用iris
数据集来传递参数。我们pmap()
用来指定变量和函数。列表列名为sq
:
iris %>%
as_tibble() %>%
mutate(sq = pmap(list(Sepal.Length, Sepal.Width), square_it))
# A tibble: 150 x 6
Sepal.Length Sepal.Width Petal.Length Petal.Width Species sq
<dbl> <dbl> <dbl> <dbl> <fct> <list>
1 5.1 3.5 1.4 0.2 setosa <tibble [1 x 2]>
2 4.9 3 1.4 0.2 setosa <tibble [1 x 2]>
3 4.7 3.2 1.3 0.2 setosa <tibble [1 x 2]>
4 4.6 3.1 1.5 0.2 setosa <tibble [1 x 2]>
5 5 3.6 1.4 0.2 setosa <tibble [1 x 2]>
6 5.4 3.9 1.7 0.4 setosa <tibble [1 x 2]>
7 4.6 3.4 1.4 0.3 setosa <tibble [1 x 2]>
8 5 3.4 1.5 0.2 setosa <tibble [1 x 2]>
9 4.4 2.9 1.4 0.2 setosa <tibble [1 x 2]>
10 4.9 3.1 1.5 0.1 setosa <tibble [1 x 2]>
# ... with 140 more rows
只需添加%>% unnest(sq)
到该代码,以生成列x
和y
:
iris %>%
as_tibble() %>%
mutate(sq = pmap(list(Sepal.Length, Sepal.Width), square_it)) %>%
unnest(sq)
# A tibble: 150 x 7
Sepal.Length Sepal.Width Petal.Length Petal.Width Species x y
<dbl> <dbl> <dbl> <dbl> <fct> <dbl> <dbl>
1 5.1 3.5 1.4 0.2 setosa 26.0 12.2
2 4.9 3 1.4 0.2 setosa 24.0 9
3 4.7 3.2 1.3 0.2 setosa 22.1 10.2
4 4.6 3.1 1.5 0.2 setosa 21.2 9.61
5 5 3.6 1.4 0.2 setosa 25 13.0
6 5.4 3.9 1.7 0.4 setosa 29.2 15.2
7 4.6 3.4 1.4 0.3 setosa 21.2 11.6
8 5 3.4 1.5 0.2 setosa 25 11.6
9 4.4 2.9 1.4 0.2 setosa 19.4 8.41
10 4.9 3.1 1.5 0.1 setosa 24.0 9.61
# ... with 140 more rows
推荐阅读
- c++ - GSSAPI:InitializeSecurityContext 返回的错误 0x80090311
- delphi - 如何对齐由 TImage 控件制成的自定义菜单,以便它可以正确拉伸到各种分辨率?
- python - matplotlib 加载内存并且不显示绘图
- java - Java:检查一个数组中的重复值并将一个更简单的 ID 分配给另一个相同大小的数组
- date - 在 sparksql 中将特定的字符串格式转换为日期
- global-variables - 在窗口对象Javascript中存储全局变量
- flutter - Flutter webview 无法将网页与屏幕匹配
- python - Django 测试导入使用来自真实数据库的内容类型值
- r - 地图上每个纬度和经度位置的 3D 点 (x, y, z) 子图
- python-3.x - 从python中的文本文件中读取元组列表