mercredi 10 juin 2020

R: Pushing entire row to NA based on condition in one column at a time

Assume df:

A   B   C   D   E   F
1   10  NA  10  NA  10
10  NA  10  1   10  10
10  1   1   NA  NA  NA
10  10  NA  10  10  10
10  NA  10  10  1   10

What I wish to do is to loop through columns to check values for each rows with following conditions:

  • A < 5 or NA
  • C < 3 or NA
  • E < 7 or NA
  • F < 2 or NA

...and subsequently, with rows in the looped column matching respective condition, the entire row will be pushed to NA

Desired outcome:

A   B   C   D   E   F
NA  NA  NA  NA  NA  NA
10  NA  10  1   10  10
NA  NA  NA  NA  NA  NA
NA  NA  NA  NA  NA  NA
NA  NA  NA  NA  NA  NA

I tried doing this to one of the columns:

df[df$A<5, ] <- NA

However this caused the error of

Error in `[<-.data.frame`(`*tmp*`, df$A < 5, , value = NA) : 
  missing values are not allowed in subscripted assignments of data frames

Please advise

Aucun commentaire:

Enregistrer un commentaire