How to mutate a specific column into categorical values

Hi there,

I am trying to mutate one variable in a dataframe into a categorical value without changing the other variables.

Here is some sample data:

DF <-data.frame(
          ID = c(1L, 2L, 3L, 4L, 5L, 6L),
    Software = c(1L, 0L, 0L, 0L, 1L, 0L),
   Expertise = c(1L, 3L, 1L, NA, 2L, 4L),
  Confidence = c(2L, NA, 4L, 5L, 3L, 2L)
)

I normally use this code

DF %>% dplyr::mutate_if(is.numeric, factor, levels = 1:5, labels = lbs) %>% drop_na() %>% as.data.frame()

but this only works if the other columns are not numeric (including the ID variable). In the above dataframe, both Expertise and Confidence are categorical variables using different scales - hence the need to only mutate one column at a time. I've tried this:

DF %>%
  dplyr::mutate_at(vars(contains("Expertise")), ~(1=="Not a barrier", 2=="Minor barrier", 3=="Major barrier", 4=="No answer"))%>%
  as.data.frame()

and

DF %>%
  dplyr::mutate_at(vars(contains("Expertise")), funs(1=="Not a barrier", 2=="Minor barrier", 3=="Major barrier", 4=="No answer"))%>%
  as.data.frame()

which produces:

Any help or advice would be much appreciated.

Simply with "case_when"? (if I understand the question correctly):

    Expertise_Cat = case_when(
      Expertise == 1 ~ "Not a barrier",
      Expertise == 2 ~ "Minor barrier",
      Expertise == 3 ~ "Major barrier",
      TRUE ~ "no answer" )    )

  ID Software Expertise Confidence Expertise_Cat
1  1        1         1          2 Not a barrier
2  2        0         3         NA Major barrier
3  3        0         1          4 Not a barrier
4  4        0        NA          5     no answer
5  5        1         2          3 Minor barrier
6  6        0         4          2     no answer
1 Like

Thank you very much @Matthias! That worked exactly as expected. Really appreciate your help.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.