Posts

Showing posts from March 6, 2019

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

Image
0 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