[英]How calculate sum of positive values in each variable of dataframe in R
I have dataframe with any number of numeric variables 我有任意数量的数字变量的数据框架
d <- data.frame(X1 = c(-1, -2, 0), X2 = c(10, 4, NA), X3 = c(-4, NA, NA))
How I may calculate the sum of positive values for each variable to keep them in the list, and if the variable has no positive values or all the values NA, return to this variable is 0. 我如何计算每个变量的正值之和以使它们保持在列表中,如果变量没有正值或所有值NA,则返回此变量为0。
We can use the apply
and ifelse
functions to iterate through each column and replace NA
or negative values with 0
我们可以使用apply
和ifelse
函数迭代每列,并用0
替换NA
或负值
apply(d, 2, function(x) sum(ifelse(is.na(x) | x < 0, 0, x)))
As @joel.wilson pointed out, there is a more concise way of coding the logic: 正如@ joel.wilson指出的那样,有一种更简洁的逻辑编码方式:
apply(d, 2, function(x) sum(x[x > 0], na.rm = TRUE))
library(expss)
d <- data.frame(X1 = c(-1, -2, 0), X2 = c(10, 4, NA), X3 = c(-4, NA, NA))
sum_col_if(gt(0), d)
# X1 X2 X3
# 0 14 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.