Home > front end >  Transform each column factors in a column containing just `0` or `1`
Transform each column factors in a column containing just `0` or `1`

Time:12-04

I'm trying to transform each of my column factors in a column containing just 0 or 1. Probably there is a function for that, or someone else already asked, but I couldn't found it. Here is a simple example to try to show what I need:

test = data.frame(my_groups = c("A", "A", "A", "B", "B", "C", "C", "C", "C"),
                  measure1 = c(1:9))

#as result:
#     group_A   group_B  group_C   measure1
# 1         1        0         0          1
# 1         1        0         0          2
# 1         1        0         0          3
# 1         0        1         0          4
# 1         0        1         0          5
# 1         0        0         1          6
# 1         0        0         1          7
# 1         0        0         1          8
# 1         0        0         1          9

Any hint on how can I do that?

CodePudding user response:

We may use dummy_cols from fastDummies

library(fastDummies)
library(dplyr)
test %>% 
    rename(group = 'my_groups') %>%
    dummy_cols('group', remove_selected_columns = TRUE) %>%    
    select(starts_with('group'), measure1)

-output

 group_A group_B group_C measure1
1       1       0       0        1
2       1       0       0        2
3       1       0       0        3
4       0       1       0        4
5       0       1       0        5
6       0       0       1        6
7       0       0       1        7
8       0       0       1        8
9       0       0       1        9
  • Related