我有一个data.frame,我们称之为“ df”。
我正在尝试创建一列,我们称其为“结果”,将其他四列加起来。
使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句