Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

Using the forcats package instead of base R

I first discretise a continuous variable using the code below:

ChickWeight2 <-
  mutate(ChickWeight,
         weight5 = case_when(weight <= 50 ~ 1,
                             weight > 50 & weight <= 100 ~ 2,
                             weight > 100 & weight <= 150 ~ 3,
                             weight > 150 & weight <= 200 ~ 4,
                             TRUE ~ 5))

and then turn this discrete variable into an ordinal one using base-R functions:

ChickWeight2 <- mutate(ChickWeight2, weight5_2 =
                  factor(weight5, levels = c(1, 2, 3, 4, 5),
                                  labels = c("very little", "litle",
                                             "medium","big","very big"),
                                  ordered = TRUE))

How can I create this ordinal variable using the functions from the forcats package instead of base R?

question from:https://stackoverflow.com/questions/65930471/using-the-forcats-package-instead-of-base-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think fct_recode is closer to what you want where you can manually specify new labels to original factor.

library(dplyr)
library(forcats)

ChickWeight2 %>%
  mutate(weight5_2 = fct_recode(weight5, "very little" = "1", "litle" = "2", 
                                "medium" = "3", "big" = "4", "very big" = 5))

But this does not give ordered factor as in the base R attempt.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...