Replacing 0 by NA if numeric and within a specific range

Hi,
I have this simple df:

source <- data.frame(
  stringsAsFactors = FALSE,
                     URN = c("bbb","ccc","hhh",
                             "aaa","ddd","eee","fff","ggg","iii"),
                    QF16 = c("No","No","No",
                             "No","Yes","Yes","Yes","Yes","Yes"),
  QF14 = c(2, 2, 0, 1, 0, 1, 1, 1, 1),
  QF70 = c(0, 6, 0, NA, 8, 10, 0, 5, NA),
  QF2 = c(0, 4, 0, 3, 2, 0, 5, 5, 5),
  QF4 = c(10, 10, 0, 8, 9, 10, 7, 10, 10)
      )

Values are incorrect as all 0 should be NAs in some of the variables.
How can I replace them globally (all numeric variables 0-2 or 0-10)?
I think I may use:

mutate(
    across(
      where(~ is.numeric(.) & all(. <= 2, na.rm = TRUE)),

and

mutate(
    across(
where(~ is.numeric(.) & any(. > 5 & .<=10, na.rm = TRUE)),

but I don't know how.
As a result I need QF14, QF70 and QF4 to be fixed like that:

result<- data.frame(
  stringsAsFactors = FALSE,
                     URN = c("bbb","ccc","hhh",
                             "aaa","ddd","eee","fff","ggg","iii"),
                    QF16 = c("No","No","No",
                             "No","Yes","Yes","Yes","Yes","Yes"),
  QF14 = c(2, 2, NA, 1, NA, 1, 1, 1, 1),
  QF70 = c(NA, 6, NA, NA, 8, 10, NA, 5, NA),
  QF2 = c(0, 4, 0, 3, 2, 0, 5, 5, 5),
  QF4 = c(10, 10, NA, 8, 9, 10, 7, 10, 10)
      )

Can you help?

This produces your desired output

library(dplyr)

source <- data.frame(
    stringsAsFactors = FALSE,
    URN = c("bbb","ccc","hhh",
            "aaa","ddd","eee","fff","ggg","iii"),
    QF16 = c("No","No","No",
             "No","Yes","Yes","Yes","Yes","Yes"),
    QF14 = c(2, 2, 0, 1, 0, 1, 1, 1, 1),
    QF70 = c(0, 6, 0, NA, 8, 10, 0, 5, NA),
    QF2 = c(0, 4, 0, 3, 2, 0, 5, 5, 5),
    QF4 = c(10, 10, 0, 8, 9, 10, 7, 10, 10)
)

source %>% 
    mutate(across(where(~ is.numeric(.) & (all(.[.!=0] <= 2, na.rm = TRUE) | (all(.[.!=0] >= 5 & .[.!=0]<=10, na.rm = TRUE)))),
    .fns = ~if_else(. == 0, NA_real_, .)))
#>   URN QF16 QF14 QF70 QF2 QF4
#> 1 bbb   No    2   NA   0  10
#> 2 ccc   No    2    6   4  10
#> 3 hhh   No   NA   NA   0  NA
#> 4 aaa   No    1   NA   3   8
#> 5 ddd  Yes   NA    8   2   9
#> 6 eee  Yes    1   10   0  10
#> 7 fff  Yes    1   NA   5   7
#> 8 ggg  Yes    1    5   5  10
#> 9 iii  Yes    1   NA   5  10

Created on 2021-09-07 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.