转换仅包含“0”或“1”的列中的每个列因子

DR1*_*R15 3 r dataframe dplyr

0我正在尝试将每个列因子转换为仅包含或 的列1。可能有一个功能,或者其他人已经问过,但我找不到它。这是一个简单的例子来尝试展示我所需要的:

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

Run Code Online (Sandbox Code Playgroud)

关于我该怎么做的任何提示?

akr*_*run 5

我们可以使用dummy_cols来自fastDummies

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

-输出

 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
Run Code Online (Sandbox Code Playgroud)