Hannah Miriam Dancy
Hannah Miriam Dancy

Reputation: 25

Assign numerical values to factor column

I posted this question a month ago and after updating R and Rstudio I am now encountering the same issue.

I am looking to convert factors to leveled numeric data.

So a column of Prox would read: Far, Far, Near, On, Far, Near, Far, Far, Near, Far.

I would like to assign numeric value to these factors, where Far is 1, Near is 2, On is 3.

Using either of these codes below

levels(Prox) levels(Prox) <- c(1, 2, 3)

OR

Prox_df <- Prox_df %>% mutate(Prox_df = case_when(Prox == "Far" ~ 3, Prox == "Near" ~ 2, Prox == "On" ~ 1))

resulted in NA coercions.

I have tried setting levels to these factors but this did not assign the numeric value. I need to use this leveled, numeric value for an ordinal model. If you have any suggestions please let me know. Thank you.

Upvotes: 0

Views: 1573

Answers (2)

hello_friend
hello_friend

Reputation: 5788

Base R solution:

Prox_df$Prox <- as.integer(as.factor(Prox_df$Prox))

Using data from @HNSKD (thank you):

Prox_df <- data.frame(Prox = c("Far", "Far", "Near", "On", "Far", "Near", "Far", "Far", "Near", "Far"), 
                      stringsAsFactors = FALSE)

Upvotes: 1

HNSKD
HNSKD

Reputation: 1644

The dplyr::case_when should work fine.

Data:

Prox_df <- data.frame(Prox = c("Far", "Far", "Near", "On", "Far", "Near", "Far", "Far", "Near", "Far"), 
                      stringsAsFactors = FALSE)

dplyr::case_when

Prox_df <- Prox_df %>%
  mutate(Prox_df = case_when(Prox == "Far" ~ 1,
                             Prox == "Near" ~ 2,
                             Prox == "On" ~ 3))

dplyr::recode

Prox_df <- Prox_df %>%
  mutate(Prox_df = recode(Prox, "Far" = 1, "Near" = 2, On = 3))

base::factor

Prox_df <- Prox_df %>%
  mutate(Prox_df = factor(Prox, levels = c("Far", "Near", "On"), labels = 1:3, ordered = TRUE))

Upvotes: 2

Related Questions