简体   繁体   English

R 中列的条件总和

[英]conditional sum of columns in R

I need a quick hint how to calculate the sum of all columns (here named A, B, C) which are greater or equal to some threshold (defined in column key).我需要一个快速提示,如何计算大于或等于某个阈值(在列键中定义)的所有列(此处命名为 A、B、C)的总和。

df <- data.frame(
  key = c(0.5, 0.8, 0.2),
  A = c(0.7, 0.6, NA),
  B = c(0.7, 0.8, 0.9),
  C = c(0.1, NA, NA)
)

The solution can be achieved with if statement, but I am looking for some more efficient way.该解决方案可以使用 if 语句来实现,但我正在寻找一些更有效的方法。

df$solution <- NA
for (i in 1:nrow(df)){
  threshold <- df[i, "key"]
  values <- df[i, c(2:ncol(df))]
  a <- sum(values[values >= threshold], na.rm = TRUE)
  df[i, "solution"] <- a
}

> df
  key   A   B   C solution
1 0.5 0.7 0.7 0.1      1.4
2 0.8 0.6 0.8  NA      0.8
3 0.2  NA 0.9  NA      0.9

I found some examples here , here and here where threshold is predefined value, but can't make it work for my case.我在此处此处此处找到了一些示例,其中阈值是预定义的值,但无法使其适用于我的情况。

df$solution <- rowSums(df[-1] * (df[,-1]>=df[,1]), na.rm = TRUE)
df
  key   A   B   C solution
1 0.5 0.7 0.7 0.1      1.4
2 0.8 0.6 0.8  NA      0.8
3 0.2  NA 0.9  NA      0.9

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

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