简体   繁体   English

如果R的均值/和均为正数或负数

[英]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. 我是R的新手,有一个快速问题。我有两列。 Most values in the columns are positive, some are 0 (there are never 2 negative values in the same row). 列中的大多数值为正,有些为0(同一行中永远不会有2个负值)。 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. 我本打算尝试一个if循环,但是我觉得可能有一种更简单的方法。 Thanks a lot! 非常感谢!

Here is a solution using data.table and ifelse() as suggested by @akrun 这是data.table建议的使用data.tableifelse()的解决方案

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 您首先将两个数字相加,然后将它们除以1或2(取决于其中一个是否为0),使用

apply(cbind(X1$ASE_1>0,X1$ASE_2>0),1,sum) 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. 这将合计布尔值(True + False = 1,True + True = 2,False + True = 1),从而提供正确的分母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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