简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM