Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, using dplyr::mutate with ifelse containing a grepl() gives unexpected result

What is wrong with this ifelse statement.

df <- data.frame(var1=c('ABC','CAB', 'AB'))
dplyr::mutate(df, var2=ifelse(grepl('^AB',var1), 'AB-starter', var1))

Gives

  var1       var2
1  ABC AB-starter
2  CAB          3
3   AB AB-starter

I wanted (using mutate and a ifelse statement) the value of var1 in second element of var2 (that is when 'var1' does not start with "AB"):

  var1       var2
1  ABC AB-starter
2  CAB        CAB
3   AB AB-starter
like image 229
user3375672 Avatar asked Oct 14 '16 13:10

user3375672


1 Answers

As 'var1' is a factor, it gets coerced to integer value within ifelse. We can avoid it by as.character

mutate(df, var2=ifelse(grepl('^AB',var1), 'AB-starter', as.character(var1)))

or when creating the data.frame, use stringsAsFactors=FALSE

like image 173
akrun Avatar answered Oct 05 '22 02:10

akrun