SushantG
SushantG

Reputation: 83

Set factors as strings while using ifelse/if

Data 'abc' is as below -

Org_Region  Dest_Region Org_City    Dest_City
WEST    EAST    BHI AAA
NORTH   WEST    DEL BHI
SOUTH   EAST    SHD AAA
WEST    NORTH   BHI ABA
NORTH   NORTH   DEL ABA
SOUTH   NORTH   SHD ABA
WEST    NORTH   BHI ABA
WEST    WEST    BHI BHI
NORTH   SOUTH   DEL ADB
SOUTH   SOUTH   SHD ADB

in the above data, I want to introduce a new column named 'Region' which looks like an excel formula -

IF(Org_City=Dest_City,"Same City",IF(Org_Region= Dest_Region,"Same Region","Rest"))

when I try the below syntax -

abc$Region <- with(abc, ifelse(abc$Org_City == abc$Dest_City, "Same City", ifelse(abc$Org_Region == abc$Dest_Region, "Same Region", "Rest")))

the error I get is -

Error in Ops.factor(abc$Org_City, abc$Dest_City) : level sets of factors are different

Upvotes: 2

Views: 49

Answers (2)

Sotos
Sotos

Reputation: 51592

abc[] <- lapply(abc, as.character)
with(abc, ifelse(Org_City == Dest_City, "Same City", 
                              ifelse(Org_Region == Dest_Region, "Same Region", "Rest")))
# [1] "Rest"        "Rest"        "Rest"        "Rest"      
#       "Same Region" "Rest"        "Rest"        "Same City"   "Rest"        "Same Region"

Side Note. You don't need to specify the data frame for every variable when using with

If we want to keep factors, then:

ifelse(as.character(abc$Org_City) == as.character(abc$Dest_City),
       "Same City",
       ifelse(as.character(abc$Org_Region) == as.character(abc$Dest_Region),
              "Same Region", "Rest"))

Upvotes: 3

Diego Aguado
Diego Aguado

Reputation: 1596

Try the following: First convert from factor to string:

dataframe$Org_Region = as.character(dataframe$Org_Region)
dataframe$Dest_Region = as.character(dataframe$Dest_Region)

Then define a function and use sapply

define_region <- function(org_city,dest_city){
if(org_city == des_city){
Region = "Same city"
} else{
Region = "Rest"}
}
dataframe$Region = sapply(dataframe$org_city,define_region,dataframe$dest_city,USE.NAMES = FALSE)

Upvotes: 1

Related Questions