问题描述
在我的数据集中,一列包含一个整数,该整数编码在进行医疗程序后是否出现“无”(0),“轻微”(1)或“严重”(2)出血。
如何将这些整数值转换为描述性名称?我尝试使用factor(levels = bleed,labels = c("none","slight","severe"))
来做到这一点,但是这与我的Tidyverse风格的%>%
管道式数据处理方法不同。
如何将这些数字变成描述性标签?
解决方法
如果只将一个整数添加到整数向量,则可以使用简单的索引。
在基数R中,它看起来像:
bleeding <- c(0,1,2,1)
values <- c("no","slight","severe")
bleeding <- values[bleeding + 1]
bleeding
#> [1] "no" "slight" "no" "slight" "slight" "no" "severe" "severe"
#> [9] "no" "slight"
或在tidyverse中:
df <- data.frame(bleeding = c(0,1))
df %>% mutate(bleeding = c("no","severe")[bleeding + 1])
#> bleeding
#> 1 no
#> 2 slight
#> 3 no
#> 4 slight
#> 5 slight
#> 6 no
#> 7 severe
#> 8 severe
#> 9 no
#> 10 slight
,
在类似tidyverse的管道中,您可以在recode
语句中使用mutate
函数
library(dplyr)
df %>%
mutate(your_int_var = recode(your_int_var,`0` = 'no',`1` = 'slight',`2` = 'severe'))
甚至使用unquote拼接!!!
values <- c(`0` = 'no',`2` = 'severe')
df %>%
mutate(your_int_var = recode(your_int_var,!!!values))