0

Beginner in R and looking to avoid unnecessary copy+pasting...

I have a data frame with a numeric column. I would like to create binary columns based on the values in the numeric column.

I know the tedious approach would be to copy+paste the following and manually add the different values:

DataFrame$NewCol1 <- as.numeric(DataFrame$ExistingCol == 1);

DataFrame$NewCol2 <- as.numeric(DataFrame$ExistingCol == 2);

Would a "for" loop be able to accomplish this task?

cnorth
  • 3
  • 1

1 Answers1

0

How about something like this?

model.matrix(~factor(DataFrame$ExistingCol))[,-1]
Yannis Vassiliadis
  • 1,719
  • 8
  • 14
  • Sorry for delay, this worked for me. But I actually found a better solution as well. library(mlr) df <- createDummyFeatures(df, cols = "df$Col") – cnorth Jul 17 '17 at 19:04