如何在向量中仅对一个符号值求和

Bar*_*aby 2 r

我有一个具有正值和负值的平均值,并希望将负值和正值分开加起来.

如果我这样做,我加上具有正号的元素的数量,但不是具有正值的元素的值.

sum(x>0) 
Run Code Online (Sandbox Code Playgroud)

如何在向量中分别添加正值和负值

谢谢

Jul*_*ano 5

x>0 判断元素是否为正数:

> x <- c(-1, -10, 6, 7, -5)
> x>0
[1] FALSE FALSE  TRUE  TRUE FALSE # elements at positions 3 and 4 are positive
Run Code Online (Sandbox Code Playgroud)

您现在可以使用它which来选择满足该条件的元素的索引:

> which(x>0)
[1] 3 4 # x[3] and x[4] meet the condition
Run Code Online (Sandbox Code Playgroud)

剩下的就是那里:

> sum(x[which(x>0)])
[1] 13
> sum(x[which(x<0)])
[1] -16
Run Code Online (Sandbox Code Playgroud)

R还与工作的载体FALSE- TRUE索引向量,所以你可以简单地这样做,以及:

> sum(x[x>0])
[1] 13
> sum(x[x<0])
[1] -16
Run Code Online (Sandbox Code Playgroud)