user13001000
user13001000

Reputation:

ifelse using some conditions in R

my data set is similar to this and I want to use ifelse or other functions in R. I can do it easily in Excel, but not sure how to do it it in R.

df<-read.table(text=" Items Goods

Mug1    Cup1
Mug1    Mug2
Mug1    NA
Mug2    Mug1
Mug2    Cup2
Cup1    Mug1
Cup2    Mug2
Mug2    Cup1
Cup1    Mug2", header=TRUE)

Conditions are:

Mug1=Cup1
Mug2=Cup2
Cup1=Mug1
Cup2=Mug2

If I see the above condition, They are considered as correct. otherwise they are incorrect. I have searched, but I could not find any solution, but it is likely I have missed some websites. Any help

I will get this table then

Items   Goods   Out
Mug1    Cup1    Correct
Mug1    Mug2    Incorrect
Mug1    NA  NA
Mug2    Mug1    Incorrect
Mug2    Cup2    Correct
Cup1    Mug1    Correct
Cup2    Mug2    Correct
Mug2    Cup1    Incorrect
Cup1    Mug2    Incorrect

Upvotes: 0

Views: 73

Answers (2)

Gonzalo Falloux Costa
Gonzalo Falloux Costa

Reputation: 372

There you go:

library(dplyr)
df<- df%>% mutate(out = ifelse(gsub("Mug","Cup",Items)==gsub("Mug","Cup",Goods),"correct","incorrect"))

Upvotes: 0

akrun
akrun

Reputation: 887038

In base R, we can use a named vector, replace the values in 'Goods' by using the named vector, do a comparison (==) with 'Items' to return a logical vector, which can be either used in ifelse or convert to a position index and replace values based on that index to 'Correct', 'Incorrect'

nm1 <- setNames(c("Mug1", "Mug2"), c("Cup1", "Cup2"))
nm2 <- c(nm1, setNames(names(nm1), nm1))
df$Out <-  with(df, c("Incorrect", "Correct")[1 + (as.character(Items) == 
    nm2[as.character(Goods)])])
df
#  Items Goods       Out
#1  Mug1  Cup1   Correct
#2  Mug1  Mug2 Incorrect
#3  Mug1  <NA>      <NA>
#4  Mug2  Mug1 Incorrect
#5  Mug2  Cup2   Correct
#6  Cup1  Mug1   Correct
#7  Cup2  Mug2   Correct
#8  Mug2  Cup1 Incorrect
#9  Cup1  Mug2 Incorrect

Or with ifelse

with(df, unname(ifelse(as.character(Items) == 
    nm2[as.character(Goods)], "Correct", "Incorrect")))
#[1] "Correct"   "Incorrect" NA          "Incorrect" "Correct"   
#[6] "Correct"   "Correct"   "Incorrect" "Incorrect"

Upvotes: 2

Related Questions