12345
12345

Reputation: 67

ifelse not working in R

I have the following variables:

a              
welcome       
put to
look at
sorted for

I want to search strings in:

if have string "come" then b="home"
if have string "to" then b="where"
if have string "sorted" then b="done"
if have string "look" then b="great"

Output

a              b
welcome        home      
put to         where
look at        great
sorted for     done

I tried below code.

let$b <- ifelse(grepl("come", let$a), "home",
         ifelse(grepl("to", let$a), "where", 
         ifelse(grepl("sorted", let$a), "done",
         ifelse(grepl("look", let$a), "great","")))

The code above is not working properly.

Upvotes: 0

Views: 7347

Answers (2)

Sam
Sam

Reputation: 518

I am posting this here with the hope it helps. Another possibility for an ifelse statement not working, which caused me to find this page, is a trailing blank.

This is obvious, but note when viewing the variable in a dataframe, even highlighting it to see what is occupying the cell space, RStudio (I am using Version 1.0.153) does not show the trailing space.

Using paste(df$var) will show spaces though. Also, you can use strip.white=TRUE when your read in the data or df$var <- trim(df$var) to trim it.

Upvotes: 1

akrun
akrun

Reputation: 886948

I would assume the column 'a' to be factor class. If that is the case, convert the column to character class and then apply the code

let$a <- as.character(let$a)
let$b <- ifelse(grepl("come", let$a), "home",
         ifelse(grepl("to", let$a), "where", 
         ifelse(grepl("sorted", let$a), "done",
         ifelse(grepl("look", let$a), "great",""))))
let$b
#[1] "home"  "where" "great" "done" 

Also, we could avoid the nested ifelse by creating vector of patterns ('pat') and replacements ('repl'), loop through the 'pat', get the numeric index of matching pattern in the 'a' column with grep and use that to get the corresponding 'repl'.

pat <- c("come", "to", "sorted", "look")
repl <- c("home", "where", "done", "great")
let$b <- repl[sapply(pat, grep, let$a)]
let$b
#[1] "home"  "where" "great" "done" 

Upvotes: 1

Related Questions