Search code examples
rdataframedata-cleaning

How to convert a dataframe from questions based columns to answers based columns


I have this example dataframe

questions = data.frame(subjects = 1:8,
                       are_you_sad = c(1,1,2,3,4,5,3,2),
                       are_you_worried = c(1,3,1,2,2,4,5,3))

and I want to convert it to:

questions = data.frame(subjects = 1:8,
                       are_you_sad_1 = c(1,1,0,0,0,0,0,0),
                       are_you_sad_2 = c(0,0,1,0,0,0,0,1),
                       are_you_sad_3 = c(0,0,0,1,0,0,1,0),
                       are_you_sad_4 = c(0,0,0,0,1,0,0,0),
                       are_you_sad_5 = c(0,0,0,0,0,1,0,0),
                       are_you_worried_1 = c(1,0,1,0,0,0,0,0),
                       are_you_worried_2 = c(0,0,0,1,1,0,0,0),
                       are_you_worried_3 = c(0,1,0,0,0,0,0,1),
                       are_you_worried_4 = c(0,0,0,0,0,1,0,0),
                       are_you_worried_5 = c(0,0,0,0,0,0,1,0)
                       )

can someone guide me through a simple function to make that possible? thanks.


Solution

  • Use fastDummies::dummy_cols:

    library(fastDummies)
    dummy_cols(questions, 
               select_columns = c("are_you_sad", "are_you_worried"), 
               remove_selected_columns = TRUE)