与 plyr
一起工作时我经常发现使用 adply
很有用对于我必须应用于每一行的标量函数。
例如
data(iris)
library(plyr)
head(
adply(iris, 1, transform , Max.Len= max(Sepal.Length,Petal.Length))
)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species Max.Len
1 5.1 3.5 1.4 0.2 setosa 5.1
2 4.9 3.0 1.4 0.2 setosa 4.9
3 4.7 3.2 1.3 0.2 setosa 4.7
4 4.6 3.1 1.5 0.2 setosa 4.6
5 5.0 3.6 1.4 0.2 setosa 5.0
6 5.4 3.9 1.7 0.4 setosa 5.4
现在我正在使用
dplyr
更多,我想知道是否有一种整洁/自然的方式来做到这一点?因为这是 不是 我想要什么:library(dplyr)
head(
mutate(iris, Max.Len= max(Sepal.Length,Petal.Length))
)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species Max.Len
1 5.1 3.5 1.4 0.2 setosa 7.9
2 4.9 3.0 1.4 0.2 setosa 7.9
3 4.7 3.2 1.3 0.2 setosa 7.9
4 4.6 3.1 1.5 0.2 setosa 7.9
5 5.0 3.6 1.4 0.2 setosa 7.9
6 5.4 3.9 1.7 0.4 setosa 7.9
最佳答案
截至 dplyr 0.2(我认为)rowwise()
已实现,因此此问题的答案变为:
iris %>%
rowwise() %>%
mutate(Max.Len= max(Sepal.Length,Petal.Length))
非
rowwise
选择五年(!)之后,这个答案仍然获得了大量流量。既然给了,
rowwise
越来越不推荐使用,尽管很多人似乎觉得它很直观。帮自己一个忙,通过 Jenny Bryan 的 Row-oriented workflows in R with the tidyverse Material 来很好地处理这个主题。我发现的最直接的方法是基于 Hadley 使用
pmap
的示例之一。 :iris %>%
mutate(Max.Len= purrr::pmap_dbl(list(Sepal.Length, Petal.Length), max))
使用这种方法,您可以为
.f
中的函数 ( pmap
) 提供任意数量的参数。 .pmap
是一个很好的概念方法,因为它反射(reflect)了这样一个事实,即当您进行行明智的操作时,您实际上是在使用向量列表(数据帧中的列)中的元组。
关于r - 使用 dplyr 将函数应用于表的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21818181/