简体   繁体   中英

Means/sums in R if both are positive or one is negative

I am new to R and have a quick question.I have two columns. Most values in the columns are positive, some are 0 (there are never 2 negative values in the same row). How do I calculate the mean for the two values in each row if both values are positive, or sum if one of them is negative (to get the 'mean' of that one non-negative value)? I was going to try an if loop, but I sense there may be an easier way. Thanks a lot!

Here is a solution using data.table and ifelse() as suggested by @akrun

df <- data.frame(A = sample(-100:100, 50, replace = TRUE),
                 B = sample(0:100, 50, replace = TRUE))
library(data.table)
setDT(df)[, C := ifelse(A*B > 0, rowMeans(.SD),
                        rowSums(.SD))] # assuming "there are never 2 negative values in the same row"

Assuming that both values are never negative, here's a quick answer:

x <- data.frame(a=c(5,4,3,-1),b=c(2,-3,4,0))
x$c <- ifelse(x$a*x$b>0, rowMeans(x),rowSums(x))

Thanks a lot for your suggestions. A friend suggested something slightly different and quite elegant. You first add up the two numbers and then divide them by either 1 or 2 (depending on whether one of them is 0) using

apply(cbind(X1$ASE_1>0,X1$ASE_2>0),1,sum)

This adds up Boolean values (True + False = 1, True + True = 2, False + True = 1), providing the correct denominator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM