For every row we select it's corresponding column which needs to be changed to 1. We generate the row/column combination by using seq
(for selecting rows) and paste0
(to select columns). For all those row/column combination we use mapply
to change all the corresponding values to 1 using the not-so-famous global assignment operator.
#Generate new columns to be added
cols <- paste0("brand-", 1:3)
#Initialise the columns to 0
mydf[cols] <- 0
mapply(function(x, y) mydf[x, y] <<- 1, seq(nrow(mydf)),
paste0("brand-", mydf$brand))
mydf
# transaction quality brand brand-1 brand-2 brand-3
#1 1 NEW 1 1 0 0
#2 0 OLD 2 0 1 0
#3 1 OLD 3 0 0 1
#4 1 OLD 1 1 0 0
#5 1 OLD 2 0 1 0
#6 0 NEW 2 0 1 0
#7 0 NEW 1 1 0 0
We can remove the orginal brand
column if we no longer require it using
mydf$brand <- NULL