Home > OS >  How to convert number 1:4 into seasons character in R
How to convert number 1:4 into seasons character in R

Time:08-24

I'm currently working on a project in which I have a column called 'season'. This column contains numbers 1:4 pertaining to the 4 seasons in a year. I'm new to R and want to create a new column that has seasons characterized for each number e.g. 1 = Spring, 2 = Summer, 3 = Autumn, and 4 = Winter. Below is an image of my data frame I am working with. Any help and tips would be much appreciated.

Dataframe image

CodePudding user response:

You can use the integer vector as an index in a string (character) vector.

set.seed(123)
seasons <- c("Spring", "Summer", "Autumn", "Winter")
idx <- sample(1:4, 10, TRUE)
idx
# [1] 3 3 3 2 3 2 2 2 3 1
seasons[idx]
# [1] "Autumn" "Autumn" "Autumn" "Summer" "Autumn" "Summer" "Summer" "Summer"
# [9] "Autumn" "Spring"

CodePudding user response:

Alternative approach:

  df$seasons <- as.factor(df$season)
  levels(df$seasons) = c("Spring", "Summer", "Autumn", "Winter")
  • Related