R--小技巧--字符串一一替换

2021-11-17  本文已影响0人  小贝学生信

引用场景:比如需要将一个字符串中的所有1变为A2变为B3变为C......

test = c(1,2,2,6,5,3,4,4,1)
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(test, levels=1:6, labels=LETTERS[1:6]) %>% as.character()
# [1] "A" "B" "B" "F" "E" "C" "D" "D" "A"

注意:由于字符串的内容与levels参数值一致;levellabels参数为一一对应的关系。

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"
上一篇 下一篇

猜你喜欢

热点阅读