Replace values with NA based on condition

Viewed 16

I am currently working on my first dataset as a PhD student. I have a dataset where several conditions have not been finished. In the dataset, this is visibly when 4 or more columns in a row have the value "1" (see example below). I want all the "1" values which do not depict "real" numbers (instead, they are "NAs) replaced by NA.

Any suggestions on how I could succeed?

example <- tibble(
  a = c(1, 2, 3, 4, 5, 6, 7, 3, 4, 2, 7, 1), 
  b = c(1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 2), 
  c = c(3, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1),
  d = c(5, 1, 2, 3, 1, 1, 1, 1, 1, 4, 1, 5),
  e = c(4, 1, 3, 4, 1, 1, 1, 1, 2, 3, 7, 5),
  f = c(3, 7, 6, 1, 1, 1, 1, 2, 1, 1, 1, 1)) 

This means I have this:

       a     b     c     d     e     f
 1     1     1     3     5     4     3
 2     2     1     1     1     1     7
 3     3     1     1     2     3     6
 4     4     1     1     3     4     1
 5     5     1     1     1     1     1
 6     6     1     4     1     1     1
 7     7     2     1     1     1     1
 8     3     3     1     1     1     2
 9     4     4     1     1     2     1
10     2     5     1     4     3     1
11     7     6     1     1     7     1
12     1     2     1     5     5     1

And I need this:

       a     b     c     d     e     f
 1     1     1     3     5     4     3
 2     2     NA    NA    NA    NA    7
 3     3     1     1     2     3     6
 4     4     1     1     3     4     1
 5     5     1     NA    NA    NA    NA
 6     6     1     4     1     1     1
 7     7     2     NA    NA    NA    NA
 8     3     3     1     1     1     2
 9     4     4     1     1     2     1
10     2     5     1     4     3     1
11     7     6     1     1     7     1
12     1     2     1     5     5     1

Thank you very much!!

0 Answers
Related