简体   繁体   English

如何计算R中每个数据帧变量的正值之和

[英]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 我们可以使用applyifelse函数迭代每列,并用0替换NA或负值

apply(d, 2, function(x) sum(ifelse(is.na(x) | x < 0, 0, x)))

Edit - concision 编辑 - 简洁

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.

相关问题 如何根据 R 中的行名计算每列中的值总和? - How to calculate sum of values in each column based on row names in R? 计算与R中的另一个数据帧重叠的值的总和 - Calculate sum of values overlapping with another dataframe in R 当列相互依赖时如何计算 R dataframe 中的值 - How to calculate values in an R dataframe when columns are dependent on each other R 中正值的求和块 - Sum Blocks of Positive Values in R 向 dataframe 添加新列,其中包含一行中正值的总和和一行中的负值总和 - R - Add new columns to a dataframe containing sum of positive values in a row and sum of negative values in a row - R 计算因子变量的计数之和,作为R中数据框的子集 - Calculate the sum of the counts of a factor variable, as a subset of a dataframe in R 如何根据正负值在R中找到条件和 - How to find conditional sum in R based on positive and negative values 如何计算 R 中唯一值的总和 - How to calculate sum on unique values in R 如何:计算 R 中每个值的百分位值 - How to: calculate percentile values for each values in R 如何计算考虑第一个数据帧中的一个变量的百分比是来自另一个数据帧中不同值的总和 - How to calculate percentages considering one variable in first dataframe is an aggregated sum from different values in another data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM