cmirian
cmirian

Reputation: 2253

How to change numbers to text in column in R?

I cannot find a simple solution to my question. Yes, I am still quite new using R.

I have a factor: w$treatment==1,2,3 in my dataset w

I would like text in stead of numbers when I look in my dataset, like this

w$treatment==1 should read Surgery

w$treatment==2 should read Radiation

w$treatment==3 should read Chemotherapy

Is that possible?

Upvotes: 1

Views: 1993

Answers (3)

Pascual Esteban
Pascual Esteban

Reputation: 23

In this simple case you can also consider recode() although you may prefer case_when().

It would be like this:

    library(tidyverse)
     library(dplyr)

w$treatment <- w$treatment %>% recode(`1`= "Surgery", `2`="Radiation", `3`= "Chemotherapy")

Upvotes: 1

Hansel Palencia
Hansel Palencia

Reputation: 1036

Another option is with case_when in a mutate

library(tidyr)
library(dplyr)

w %>%
  mutate(treatment = case_when(
                     treatment == 1 ~ "Surgery",
                     treatment == 2 ~ "Radiation",
                     treatment == 3 ~ "Chemotherapy"))

Upvotes: 2

akrun
akrun

Reputation: 887028

An option is factor

w$treatment <- with(w, factor(treatment, levels = 1:3, 
                  labels = c("Surgery", "Radiation", "Chemotherapy"))

Upvotes: 4

Related Questions