使用 Tidyverse 在 R 中将整数转换为向量

Convert integers to vector in R using Tidyverse

在我的数据集中,有一列包含整数,用于编码医疗程序后是否有“无”(0)、“轻微”(1) 或“严重”(2) 出血。

如何将这些整数值转换为描述性名称?我试着用 factor(levels = bleed, labels = c("none", "slight", "severe")) 来解决它,但这不符合我的 Tidyverse 风格,%>%-管道数据整理。

如何将这些数字变成描述性标签?

如果您只需将整数向量加一,就可以使用简单索引。

在 base R 中,这看起来像:

bleeding <- c(0, 1, 0, 1, 1, 0, 2, 2, 0, 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, 0, 1, 1, 0, 2, 2, 0, 1))

df %>% mutate(bleeding  = c("no", "slight", "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 的管道中,您可以在 mutate 语句中使用 recode 函数

library(dplyr)

df %>%
  mutate(your_int_var = recode(your_int_var, `0` = 'no', `1` = 'slight', `2` = 'severe'))

或者使用反引号拼接更好!!!

values <- c(`0` = 'no', `1` = 'slight', `2` = 'severe')

df %>% 
  mutate(your_int_var = recode(your_int_var, !!!values))