I'd like to remove all rows that sum to 0, but I have factor columns in the first 2 columns. I've come up with a dplyr solution, creating an intermediate rowsum column, filtering out rows that sum to 0, then removing that rowsum column.
I'd like to find a way for this to work without creating that unnecessary rowsum column, both using base R and a dplyr/tidyverse pipe-friendly method. Surely there's an easy, one-line piece of code to make this happen?
library(tidyverse)
df <- data.frame(person = rep(c("Ed", "Sue"), 6),
id = paste0("plot",1:12),
a = c(2, 0, 0, 0, 0, 1, 0, 0, 4, 0, 0, 0),
b = c(0, 0, 6, 4, 0, 8, 1, 0, 0, 0, 1, 1),
c = c(4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 8),
d = c(0, 0, 0, 3, 0, 1, 0, 0, 9, 0, 1, 5),
e = c(7, 0, 5, 0, 0, 1, 0, 0, 0, 0, 7, 0))
##create intermediate 'row.sum' column, filter rows that have all 0's, then remove row.sum column
df1 <- df %>%
dplyr::mutate(row.sum = a+b+c+d+e) %>%
dplyr::filter(row.sum != 0) %>%
dplyr::select(-row.sum)
#end result:
# person id a b c d e
#1 Ed plot1 2 0 4 0 7
#2 Ed plot3 0 6 0 0 5
#3 Sue plot4 0 4 0 3 0
#4 Sue plot6 1 8 0 1 1
#5 Ed plot7 0 1 0 0 0
#6 Ed plot9 4 0 0 9 0
#7 Ed plot11 0 1 3 1 7
#8 Sue plot12 0 1 8 5 0