Conditionally sum dynamic columns in r

倖福魔咒の 提交于 2021-01-27 19:20:39

问题


I am trying to conditionally sum across many columns depending on if they are greater than or less than 0. I am surprised I cannot find a dplyr or data.table work around for this. I want to calculate 4 new columns for a large data.frame (columns to calculate are at bottom of post).

dat2=matrix(nrow=10,rnorm(100));colnames(dat2)=paste0('V',rep(1:10))

dat2 %>% as.data.frame() %>%
  rowwise() %>%
  select_if(function(col){mean(col)>0}) %>%
  mutate(sum_pos=rowSums(.))  ##Obviously doesn't work

These are the simple statistics I want to calculate (yes; these apply statements work, but there are other things in my dplyr chain I want to do, so thats why I am looking for a dplyr or data.table way. The columns that are positive or negative for each given row are different, so I cannot grab a list of columns (must be done dynamically, by row).

#Calculate these, but in a dplyr chain?
n_pos=apply(dat2,1,function(x) sum((x>0)))
n_neg=apply(dat2,1,function(x) sum((x<0)))
sum_pos=apply(dat2,1,function(x) sum(x[(x>0)]))
sum_neg=apply(dat2,1,function(x) sum(x[(x<0)]))

回答1:


We don't need rowwise with rowSums as rowSums can do the sum without any groupings

library(dplyr)
dat2 %>%
   as.data.frame() %>%  
   select_if(~ is.numeric(.) && mean(.) > 0) %>% 
   mutate(sum_pos = rowSums(.))

Based on the description, it seems that it is not the mean condition, but related to rowwise, sum of the positive and negative values separately

dat2 %>%
   as.data.frame %>%
   mutate(sum_pos = rowSums(. * NA^(. < 0), na.rm = TRUE),
           sum_neg = rowSums(.[1:10] * NA^(.[1:10] > 0), na.rm = TRUE) )


来源:https://stackoverflow.com/questions/59376765/conditionally-sum-dynamic-columns-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!