[英]R, using dplyr::mutate with ifelse containing a grepl() gives unexpected result
What is wrong with this ifelse statement. 这个ifelse声明有什么问题。
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"): 我想(使用mutate和ifelse语句)var2的第二个元素中var1的值(即'var1'不以“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
. 由于'var1'是一个
factor
,它会在ifelse
被强制转换为整数值。 We can avoid it by as.character
我们可以通过
as.character
来避免它
mutate(df, var2=ifelse(grepl('^AB',var1), 'AB-starter', as.character(var1)))
or when creating the data.frame
, use stringsAsFactors=FALSE
或者在创建
data.frame
,使用stringsAsFactors=FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.