0

I have a dataframe like this:

> dput(df_before)
structure(list(ID = 1:4, White = c(1L, 0L, 0L, 0L), Black = c(0L, 
1L, 0L, 0L), Asian = c(0L, 0L, 1L, 1L)), class = "data.frame", row.names = c(NA, 
-4L))

Right now the 'Race' variable is encoded as a dummy variable, but I would like it to look like this:

> dput(df_after)
structure(list(ID = 1:4, Race = c("White", "Black", "Asian", 
"Asian")), class = "data.frame", row.names = c(NA, -4L))
Jamie
  • 543
  • 7
  • https://stackoverflow.com/questions/30333401/convert-various-dummy-logical-variables-into-a-single-categorical-variable-facto – user20650 May 26 '23 at 16:30

2 Answers2

1

You can use the case_when function from the tidyverse to reshape the dataframe.

library(tidyverse)
df_after <- df_before %>% 
  mutate(Race = case_when(White == 1 ~ "White",
                          Black == 1 ~ "Black",
                          Asian == 1 ~ "Asian"))
Leonardo19
  • 83
  • 5
0

In base R, using dynamic rather than static:

cbind(df[1], Race = names(df[-1])[max.col(df[-1])])

  ID  Race
1  1 White
2  2 Black
3  3 Asian
4  4 Asian
Onyambu
  • 67,392
  • 3
  • 24
  • 53