R:求和值和求和值

时间:2022-09-15 01:32:30

I've got a vector:

我有一个矢量:

vec <- c(1,-2,9,-7,7,4,5,2,1,-10)

Now I would like to take the sum of the negative values in vec, and the sum of the positive values in vec.

现在我想取vec中负值的总和,以及vec中正值的总和。

neg <- sum of the negative values in vec
pos <- sum of the positive values in vec

2 个解决方案

#1


neg <- sum(vec[vec<0]);
pos <- sum(vec[vec>0]);

#2


Try:

pos <- sum(subset(vec, vec > 0))
neg <- sum(subset(vec, vec < 0))

Or:

l <- split(vec, vec < 0)
pos <- sum(l[[1]])
neg <- sum(l[[2]])

Or as mentioned by @David in the comments:

或者@David在评论中提到:

m <- lapply(split(vec, vec < 0), sum)
pos <- m[[1]]
neg <- m[[2]]

#1


neg <- sum(vec[vec<0]);
pos <- sum(vec[vec>0]);

#2


Try:

pos <- sum(subset(vec, vec > 0))
neg <- sum(subset(vec, vec < 0))

Or:

l <- split(vec, vec < 0)
pos <- sum(l[[1]])
neg <- sum(l[[2]])

Or as mentioned by @David in the comments:

或者@David在评论中提到:

m <- lapply(split(vec, vec < 0), sum)
pos <- m[[1]]
neg <- m[[2]]