I am working in R and I have a large dataframe with many rows and columns. The following data frame df
is a minimal example.
#Example dataframe
row1 <- c(1,2,3,4,5,6,0,8)
row2 <- c(1,0,0,0,10,0,0,0)
row3 <- c(0,1,2,3,4,5,6,0)
df <- t(data.frame(str1,str2,str3))
I would like to remove rows with >4 zero values yielding the following desired output. However this has to be done in a high throughput manner.
#Desired Output
desired_output <- df[c(1,3),]
It seems that i need to do two things.
- For each row count the number of columns containing a zero and return this information inside a loop or apply function.
- use this information to subset the broader dataset.
Here is a non-functioning attempt
outlist <- list()
for (x in 1:length(rownames(df))) {
out <- sapply(df[x,], function(x){sum(x>0)})
print(out)
append(outlist, out)
}
df[!rowSums(df == 0) > 4, ]
?