I´m trying to delete the rows in a data frame which contain zeros in the first 3 non NA elements.
As example:
> c <- matrix(c(NA,NA,4,5,0,7,0,NA,NA,NA,NA,8,9,10,0,4,5,0,NA,NA), ncol=5, nrow = 4, byrow=T)
> c
[,1] [,2] [,3] [,4] [,5]
[1,] NA NA 4 5 0
[2,] 7 0 NA NA NA
[3,] NA 8 9 10 0
[4,] 4 5 0 NA NA
I´m expecting to have an output such as: TRUE TRUE FALSE TRUE in order to create the subset without the rows with zeros in the first 3 non NA elements.
Does anyone have a simple solution for this?
We can do this with apply
. Loop through the rows, subset the non-NA elements, check whether 0 is in it
apply(c, 1, function(x) 0 %in% x[!is.na(x)][1:3])
#[1] TRUE TRUE FALSE TRUE