3
votes

I have the following data frame:

library(tidyverse)
df <- tibble(a = c(1, 2, 3, 4, 5),
             b = c("Y", "N", "N", "Y", "N"),
             c = c("A", "B", "C", "A", "B"))

df <- df %>%
  mutate_if(is.character, funs(as.factor))

The output of df:

      a b     c    
  <dbl> <fct> <fct>
1     1 Y     A    
2     2 N     B    
3     3 N     C    
4     4 Y     A    
5     5 N     B    

I would like to recode all factor (b and c variables) levels to integers: if a factor has only two levels it should be recoded to {0, 1}, otherwise to {1, 2, 3, ...} levels. So the output should be:

      a b     c    
  <dbl> <fct> <fct>
1     1 1     1    
2     2 0     2    
3     3 0     3    
4     4 1     1    
5     5 0     2    

I can recode variables separately (one by one), but I wonder if there is a more convenient approach.

3

3 Answers

3
votes
df <- df %>%
  mutate_if(
    is.character,
    function(x) {
      out <- as.integer(as.factor(x))
      if (n_distinct(out) == 2) out <- out - 1L
      out
    }
  )
df

#       a     b     c
#   <dbl> <int> <int>
# 1     1     1     1
# 2     2     0     2
# 3     3     0     3
# 4     4     1     1
# 5     5     0     2
2
votes

Does this work:

> library(dplyr)
> df %>% mutate(b_fac = match(b,unique(b)) - 1, c_fac = match(c, unique(c))) %>% 
+       mutate(b_fac = ifelse(b_fac == 1, 0, 1)) %>% mutate(b_fac = as.factor(b_fac), c_fac = as.factor(c_fac))  %>% 
+       select(-2,-3) %>% rename(b = b_fac, c = c_fac)
# A tibble: 5 x 3
      a b     c    
  <dbl> <fct> <fct>
1     1 1     1    
2     2 0     2    
3     3 0     3    
4     4 1     1    
5     5 0     2    
> 
2
votes

One dplyr option could be:

df %>%
 mutate(across(where(is.factor), 
               ~ if(n_distinct(.) == 2) factor(., labels = 0:1) else factor(., labels = 1:n_distinct(.))))

      a b     c    
  <dbl> <fct> <fct>
1     1 1     1    
2     2 0     2    
3     3 0     3    
4     4 1     1    
5     5 0     2