引用场景:比如需要将一个字符串中的所有
1
变为A
,2
变为B
,3
变为C
......
test = c(1,2,2,6,5,3,4,4,1)
- 方法一:
ifelse()
ifelse(test==1,"A",
ifelse(test==2,"B",
ifelse(test==3,"C",
ifelse(test==4,"D",
ifelse(test==5,"E","F")))))
# [1] "A" "B" "B" "F" "E" "C" "D" "D" "A"
- 方法二:
factor()
的label
factor(test, levels=1:6, labels=LETTERS[1:6]) %>% as.character()
# [1] "A" "B" "B" "F" "E" "C" "D" "D" "A"
注意:由于字符串的内容与levels
参数值一致;level
与labels
参数为一一对应的关系。
- 方法三:
dplyr::case_when
dplyr::case_when(
test==1 ~ "A",
test==2 ~ "B",
test==3 ~ "C",
test==4 ~ "D",
test==5 ~ "E",
test==6 ~ "F")
# [1] "A" "B" "B" "F" "E" "C" "D" "D" "A"
网友评论