I would like to change the type of the columns from character to ordinal with levels as no. of months in a year(i.e., 12) and no.of years(i.e.,3) respectively. My data frame is similar to the following one:
month <- c("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec")
year <- c(rep(2020,5),rep(2021,5),rep(2022,2))
df <- data.frame(month,year)
df$month <- as.factor(df$month)
df$year <-as.factor(df$year)
How can I change the levels here to the no.of months and years?
CodePudding user response:
We may use labels
df$month <- factor(df$month, levels = unique(df$month), labels = 1:12)
df$year <- factor(df$year, levels = sort(unique(df$year)),
labels = seq_along(sort(unique(df$year))))