How to transform multiple columns variables into dummy variables in Rstudio?

I have following variables f_100_0_0 and f_100_0_1. They are respreenting choosing two of your favotite colors from total 4 colors (1-red, 2-green, 3-blue and 4-white). In R, how can I change them into the dummy variables on the right side, which are 4 dummy variables representing 4 colors.

Thanks!

I would probably use scorecard::one_hot

You can do this without loading any libraries. Let's assume your data is in a dataframe named df. Try the following:

m <- model.matrix(~ as.factor(f_100_0_0) - 1, data = df)

This should produce a matrix containing the dummy variables for f_100_0_0. You can repeat this for f_100_0_1 and then use cbind to combine the matrices. You may want to rename the columns to taste.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.