samedi 24 novembre 2018

R how to change the value of a variable based on a condition using dplyr::mutate and if_else?

I'm trying to change a value of a variable in a data.frame where if a condition is met, then the variable takes another value, and if the condition is not met, the variable takes its original value. I'm confused why I'm getting an error and would like to know how can I modify my code to overcome this error.

For example, say I have the following dataset x and I want to create a new variable var3, such that if a condition is met, var3 takes 1, if not var3 takes its old value.

x = data.frame(var1 = c('a', 'b', 'ab'),
               var2 = rep(2,3))
x
x %>%
  dplyr::mutate(var3 = 0,
                var3 = if_else(grep('a', var1)==1, 1, var3))

If I run this code I get the following error

Error in mutate_impl(.data, dots) : 
  Column `var3` must be length 3 (the number of rows) or one, not 2

My real code is more complicated and I need to var3 to take its old value when the condition evaluates FALSE, rather than just a singular value (say 0).

What am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire