Menkot
Menkot

Reputation: 734

How do I simplify the replacing codes below

To replace the ClientType column with other Strings like:

#Change the label of ClientType
data$ClientType[data$ClientType=="a"]<-"Android"
data$ClientType[data$ClientType=="b"]<-"ios"
data$ClientType[data$ClientType=="c"]<-"web"
data$ClientType[data$ClientType=="d"]<-"type4"
data$ClientType[data$ClientType=="e"]<-"Type5"
...

Thank you for any comments!

Upvotes: 0

Views: 33

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

One option is to use dplyr case_when

library(dplyr)
data %>%
  mutate(ClientType = case_when(ClientType == "a" ~ "Android", 
                                ClientType == "b" ~ "ios",
                                ClientType == "c" ~ "web",
                                ClientType == "d" ~ "type4",
                                ClientType == "e" ~ "Type5",
                                TRUE ~ NA))

Another option is to use recode

recode(data$ClientType,a = "Android",b = "ios",c = "web", d = "type4", e = "type5")

Upvotes: 1

Related Questions