1

In my data set, a column holds integer numbers that encode whether there was "no" (0), "slight" (1), or "severe" (2) bleeding after a medical procedure.

How can I turn those integer values into descriptive names? I tried to to it with factor(levels = bleed, labels = c("none", "slight", "severe")), but that does not agree with my Tidyverse-style, %>%-piped data wrangling.

How do I turn those numbers into descriptive labels?

Ric S
  • 9,073
  • 3
  • 25
  • 51
bovender
  • 1,838
  • 15
  • 31
  • Does this answer your question? [Recoding variables with R](https://stackoverflow.com/questions/5372896/recoding-variables-with-r) – Ian Campbell Nov 11 '20 at 01:59

2 Answers2

1

You can use simple indexing if you just add one to your integer vector.

In base R this would look like:

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"

Or in 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
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

In a tidyverse-like pipeline, you can use the recode function inside a mutate statement

library(dplyr)

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

or even better using unquote splicing !!!

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

df %>% 
  mutate(your_int_var = recode(your_int_var, !!!values))
Ric S
  • 9,073
  • 3
  • 25
  • 51