R: ifelse on string
if-statement, r, string
Solution
I suggest you break down that deeply nested `ifelse` statement into more manageable chunks.
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...)
}
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...
Problem
I am populating a new variable of a dataframe, based on string conditions from another variable. I receive the following error msg: `Error in Source == "httpWWW.BGDAILYNEWS.COM" | Source == : operations are possible only for numeric, logical or complex types` My code is as follows: `County <- ifelse(Source == 'httpWWW.BGDAILYNEWS.COM' | 'WWW.BGDAILYNEWS.COM', 'Warren', ifelse(Source == 'httpWWW.HCLOCAL.COM' | 'WWW.HCLOCAL.COM', 'Henry', ifelse(Source == 'httpWWW.KENTUCKY.COM' | 'WWW.KENTUCKY.COM', 'Fayette', ifelse(Source == 'httpWWW.KENTUCKYNEWERA.COM' | 'WWW.KENTUCKYNEWERA.COM', 'Christian') )))`