0

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.

  1. For each row count the number of columns containing a zero and return this information inside a loop or apply function.
  2. 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)
  }
2

1 Answer 1

0
df %>% filter(rowSums(across(everything(), ~.x==0))<=4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.