为什么我不能使用 dplyr 应用函数来创建带有 mutate() 的新列?
Why can't I apply a function to create a new column with mutate() using dplyr?
我有一个data.frame,我们称它为“df”吧。
我正在尝试创建一个列,我们称它为 "result",总结其他四个列。
使用dplyr,我可以用下面的代码来完成:
mutate(df, result=col1+col2+col3+col4)
但是,当我尝试以下操作时:
mutate(df, result=sum(col1, col2, col3, col4))
它不起作用。为什么会发生?
正如所指出的,+
和 sum()
的行为不同。考虑:
> sum(1:10,1:10)
[1] 110
> `+`(1:10,1:10)
[1] 2 4 6 8 10 12 14 16 18 20
如果你真的想要 sum()
你想要的每一行的变量 rowwise()
:
library(dplyr)
df <- data_frame(w = letters[1:3], x=1:3, y = x^2, z = y - x)
# Source: local data frame [3 x 4]
#
# w x y z
# 1 a 1 1 0
# 2 b 2 4 2
# 3 c 3 9 6
df %>% rowwise() %>% mutate(result = sum(x, y, z))
# Source: local data frame [3 x 5]
# Groups: <by row>
#
# w x y z result
# 1 a 1 1 0 2
# 2 b 2 4 2 8
# 3 c 3 9 6 18
将此与以下内容进行比较:
df %>% mutate(result = x + y + z)
# Source: local data frame [3 x 5]
#
# w x y z result
# 1 a 1 1 0 2
# 2 b 2 4 2 8
# 3 c 3 9 6 18
df %>% mutate(result = sum(x, y, z)) # sums over all of x, y and z and recycles the result!
# Source: local data frame [3 x 5]
#
# w x y z result
# 1 a 1 1 0 28
# 2 b 2 4 2 28
# 3 c 3 9 6 28
我有一个data.frame,我们称它为“df”吧。
我正在尝试创建一个列,我们称它为 "result",总结其他四个列。
使用dplyr,我可以用下面的代码来完成:
mutate(df, result=col1+col2+col3+col4)
但是,当我尝试以下操作时:
mutate(df, result=sum(col1, col2, col3, col4))
它不起作用。为什么会发生?
正如所指出的,+
和 sum()
的行为不同。考虑:
> sum(1:10,1:10)
[1] 110
> `+`(1:10,1:10)
[1] 2 4 6 8 10 12 14 16 18 20
如果你真的想要 sum()
你想要的每一行的变量 rowwise()
:
library(dplyr)
df <- data_frame(w = letters[1:3], x=1:3, y = x^2, z = y - x)
# Source: local data frame [3 x 4]
#
# w x y z
# 1 a 1 1 0
# 2 b 2 4 2
# 3 c 3 9 6
df %>% rowwise() %>% mutate(result = sum(x, y, z))
# Source: local data frame [3 x 5]
# Groups: <by row>
#
# w x y z result
# 1 a 1 1 0 2
# 2 b 2 4 2 8
# 3 c 3 9 6 18
将此与以下内容进行比较:
df %>% mutate(result = x + y + z)
# Source: local data frame [3 x 5]
#
# w x y z result
# 1 a 1 1 0 2
# 2 b 2 4 2 8
# 3 c 3 9 6 18
df %>% mutate(result = sum(x, y, z)) # sums over all of x, y and z and recycles the result!
# Source: local data frame [3 x 5]
#
# w x y z result
# 1 a 1 1 0 28
# 2 b 2 4 2 28
# 3 c 3 9 6 28