如何简化下面的替换代码

时间:2019-04-17 05:11:37

标签: r

要将ClientType列替换为其他字符串,例如:

#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"
...

谢谢您的任何评论!

1 个答案:

答案 0 :(得分:1)

一种选择是使用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))

另一种选择是使用recode

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