R:字符串上的ifelse [英] R: ifelse on string
问题描述
我正在根据另一个变量的字符串条件填充数据框的新变量。我收到以下错误信息:
I am populating a new variable of a dataframe, based on string conditions from another variable. I receive the following error msg:
来源错误==httpWWW.BGDAILYNEWS.COM| Source ==:
只能对数字,逻辑或复杂类型进行操作
我的代码如下:
县< - ifelse(来源=='httpWWW.BGDAILYNEWS.COM'|'WWW.BGDAILYNEWS.COM','Warren',
ifelse(来源=='httpWWW.HCLOCAL.COM'|'WWW.HCLOCAL.COM','亨利',
ifelse(来源=='httpWWW.KENTUCKY.COM'|'WWW.KENTUCKY.COM' ,'Fayette',
ifelse(来源=='httpWWW.KENTUCKYNEWERA.COM'|'WWW.KENTUCKYNEWERA.COM','Christian')
)))
推荐答案
我建议你将深度嵌套的 ifelse
语句分解为更易于管理的块。
I suggest you break down that deeply nested ifelse
statement into more manageable chunks.
但错误告诉你不能像这样使用 |
。 'a'| 'b'
因为它是一个逻辑比较而没有意义。而是在%中使用%:
But the error is telling you that you cannot use |
like that. 'a' | 'b'
doesn't make sense since its a logical comparison. Instead use %in%
:
Source %in% c('htpWWW.BGDAILYNEWS.com', 'WWW.BGDAILYNEWS.COM')
我想......如果我理解你在做什么,你会更好地使用多个作业:
I think... If I understand what you're doing, you will be much better off using multiple assignments:
County = vector(mode='character', length=length(Source))
County[County %in% c('htpWWW.BGDAILYNEWS.com', 'WWW.BGDAILYNEWS.COM')] <- 'Warren'
etc.
您还可以使用开关
语句这类事情:
You can also use a switch
statement for this type of thing:
myfun <- function(x) {
switch(x,
'httpWWW.BGDAILYNEWS.COM'='Warren',
'httpWWW.HCLOCAL.COM'='Henry',
etc...)
}
然后你想做一个简单的申请( sapply
)传递来源
到 myfun
:
Then you want to do a simple apply (sapply
) passing each element in Source
to myfun
:
County = sapply(Source, myfun)
或者最后,你可以使用因子
和等级
,但我会将其作为练习留给读者...
Or finally, you can use factors
and levels
, but I'll leave that as an exercise to the reader...
这篇关于R:字符串上的ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!