[英]Sum across rows but only the cells that meet a condition
樣本數據:
df <- tibble(x = c(0.1, 0.2, 0.3, 0.4),
y = c(0.1, 0.1, 0.2, 0.3),
z = c(0.1, 0.2, 0.2, 0.2))
df
# A tibble: 4 x 3
x y z
<dbl> <dbl> <dbl>
1 0.1 0.1 0.1
2 0.2 0.1 0.2
3 0.3 0.2 0.2
4 0.4 0.3 0.2
我想跨行求和,我只想將滿足特定邏輯條件的“單元格”加起來。 在此示例中,我只想按行將包含等於或大於指定閾值的單元格相加。
所需 Output
threshold <- 0.15
# A tibble: 4 x 4
x y z cond_sum
<dbl> <dbl> <dbl> <dbl>
1 0.1 0.1 0.1 0
2 0.2 0.1 0.2 0.4
3 0.3 0.2 0.2 0.7
4 0.4 0.3 0.2 0.9
偽代碼
這是我心目中的爭論想法。
df %>%
rowwise() %>%
mutate(cond_sum = sum(c_across(where(~ "cell" >= threshold))))
整潔的解決方案表示贊賞!
一個有效的選擇是將低於閾值的值替換為 NA 並在na.rm
中使用rowSums
而不是rowwise/c_across
library(dplyr)
df %>%
mutate(cond_sum = rowSums(replace(., . < threshold, NA), na.rm = TRUE))
-輸出
# A tibble: 4 x 4
# x y z cond_sum
# <dbl> <dbl> <dbl> <dbl>
#1 0.1 0.1 0.1 0
#2 0.2 0.1 0.2 0.4
#3 0.3 0.2 0.2 0.7
#4 0.4 0.3 0.2 0.9
或與c_across
df %>%
rowwise %>%
mutate(cond_sum = {val <- c_across(everything())
sum(val[val >= threshold])}) %>%
ungroup
或base R
df$cond_sum <- rowSums(replace(df, df < threshold, NA), na.rm = TRUE)
dplyr
和purrr
的選項可以是:
df %>%
mutate(cond_sum = pmap_dbl(across(x:z), ~ sum(c(...)[c(...) > threshold])))
x y z cond_sum
<dbl> <dbl> <dbl> <dbl>
1 0.1 0.1 0.1 0
2 0.2 0.1 0.2 0.4
3 0.3 0.2 0.2 0.7
4 0.4 0.3 0.2 0.9
或者只使用dplyr
:
df %>%
mutate(cond_sum = Reduce(`+`, across(x:z) * (across(x:z) > threshold)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.