[英]Conditionally sum columns in R
一種tidyverse
的方法
library(dplyr)
set.seed(5)
dat <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5))
conditional_sum <- function(x,a = 0,b = 3){
sum(x[x > a & x <= b],na.rm = TRUE)
}
dat %>%
rowwise() %>%
mutate(newvar = conditional_sum(c_across()))
# A tibble: 5 x 4
# Rowwise:
a b c newvar
<dbl> <dbl> <dbl> <dbl>
1 -0.841 -0.603 1.23 1.23
2 1.38 -0.472 -0.802 1.38
3 -1.26 -0.635 -1.08 0
4 0.0701 -0.286 -0.158 0.0701
5 1.71 0.138 -1.07 1.85
將不滿足條件的元素替換為NA
,獲取元素的rowSums
上的rowSums,創建'newvar'
dat$newvar <- rowSums(NA^(dat <=0|dat >=3)*dat, na.rm = TRUE)
-輸出
> dat
a b c newvar
1 -0.84085548 -0.6029080 1.2276303 1.22763034
2 1.38435934 -0.4721664 -0.8017795 1.38435934
3 -1.25549186 -0.6353713 -1.0803926 0.00000000
4 0.07014277 -0.2857736 -0.1575344 0.07014277
5 1.71144087 0.1381082 -1.0717600 1.84954910
執行按行操作的常用方法是使用apply
function。例如:
dat$newvar <- apply(dat, 1, \(r) sum(r[r > 0 & r <= 3]))
讀作:將 function 應用於dat
的每一行。 function 采用向量r
,並對滿足條件的r
的元素求和。
結果是
a b c newvar
1 -0.84085548 -0.6029080 1.2276303 1.22763034
2 1.38435934 -0.4721664 -0.8017795 1.38435934
3 -1.25549186 -0.6353713 -1.0803926 0.00000000
4 0.07014277 -0.2857736 -0.1575344 0.07014277
5 1.71144087 0.1381082 -1.0717600 1.84954910
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.