Re-coding all numeric values into 1s

I have a simple dummy data frame.
I know how to multiply all numeric values by a number:

source <- data.frame(stringsAsFactors=FALSE,
           þÿ.URN. = c("aaa", "bbb", "ccc"),
           Recommendation_2_43 = c(3, NA, NA),
           Staff_13 = c(NA, 1, NA),
           Recommendation_1_35 = c(NA, NA, 2)
)

library(dplyr)
step1 <- source %>% 
  mutate_if(~is.numeric(.) && any(. > 0, na.rm = TRUE),
                             ~.x * 10)

but now my different task is recoding all values >=1 into 1s.
How can I do that?

step1 <- source %>% 
  mutate_if(~is.numeric(.) && any(. > 0, na.rm = TRUE),
           ~ if_else(.x>0,1,.x))

I know this issue is resolved already (thank you again for help) but what can I do if variables are integers (not numbers)?
Even if I change the code into:

  mutate_if(~is.integer(.) && any(. > 0, na.rm = TRUE),
            ~ if_else(.x>0,1,.x))

I have following error:

Error: `false` must be a double vector, not an integer vector
Call `rlang::last_error()` to see a backtrace
> 

Is recoding to num prior to this function a good solution?

library(dplyr)
source <- source %>% mutate_if(is.integer,as.numeric)
step1 <- source %>% 
  mutate_if(~is.numeric(.) && any(. > 0, na.rm = TRUE),
            ~ if_else(.x>0,1,.x))

this has an easy fix, its a shame that the error message isnt more help in diagnosing the issue...
The problem you faced is a result of the if_else() function, which has particular constraints. It wants consistent data types in each of its 3 paramers (test expression, yes exp, no exp) . if we are dealing with integers as inputs (the .x) then its wrong to set the value to 1 which to R is a double value, rather our code should set the value to 1L which is an integer.

 mutate_if(~is.integer(.) && any(. > 0, na.rm = TRUE),
            ~ if_else(.x>0,1L,.x))

Thank you very much! :grinning:
Alternatively I can convert all integers to numbers prior to the code...

 mutate_if(is.integer,as.numeric) %>% 
mutate_if(~is.numeric(.) && any(. > 0, na.rm = TRUE), ~ if_else(.x>0,1,.x))

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