R: ifelse on string -
i populating new variable of dataframe, based on string conditions variable. receive following error msg:
error in source == "httpwww.bgdailynews.com" | source == : operations possible numeric, logical or complex types
my code 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') )))
i suggest break down nested ifelse statement more manageable chunks.
but error telling you cannot use | that. 'a' | 'b' doesn't make sense since logical comparison. instead use %in%:
source %in% c('htpwww.bgdailynews.com', 'www.bgdailynews.com') i think... if understand you're doing, 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 use switch statement type of thing:
myfun <- function(x) { switch(x, 'httpwww.bgdailynews.com'='warren', 'httpwww.hclocal.com'='henry', etc...) } then want simple apply (sapply) passing each element in source myfun:
county = sapply(source, myfun) or finally, can use factors , levels, i'll leave exercise reader...
Comments
Post a Comment