Home > Net >  change a numeric column to a factor and assign labels/levels to the data
change a numeric column to a factor and assign labels/levels to the data

Time:11-05

I have a numeric column with values 1,2 and 3 I want to change it to a factor column and assign values i.e., 1 = Petrol, 2 = Hybrid and 3 = Diesel without changing the original data how do I do that?

CodePudding user response:

You may try using levels function. For example dummy data with three factor 1, 2 and 3,

dummy <- data.frame(
  fac = rep(c(1,2,3),4)
)
dummy$fac <- as.factor(dummy$fac)

In base R

R-1

levels(dummy$fac) <- c("Petrol", "Hybrid", "Disesel")

R-2

levels(dummy$fac) <- list("Petrol" = 1, "Hybrid" = 2, "Disesel" = 3)

Also, using dplyr package,

dplyr

dummy$fac <- dplyr::recode_factor(dummy$fac, "1" = "Petrol", "2" = "Hybrid" , "3" = "Disesel")

All will give

       fac
1   Petrol
2   Hybrid
3  Disesel
4   Petrol
5   Hybrid
6  Disesel
7   Petrol
8   Hybrid
9  Disesel
10  Petrol
11  Hybrid
12 Disesel

And str(dummy$fac) is like

Factor w/ 3 levels "Petrol","Hybrid",..: 1 2 3 1 2 3 1 2 3 1 ...
  •  Tags:  
  • r
  • Related