I have a data table and I want to create a new column for each unique day, and then assign a 1 in each row where the day matches the column name
I have done this using a for loop but I was wondering if there was any way to optimise it using data.table and set?
Here is an example
dt <- data.table(Week_Day = c("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"))
Day <- unique(dt$Week_Day)
for (i in 1:length(Day)) {
if (Day[i] != "Sunday") {
dt[, Day[i] := ifelse(Week_Day == Day[i], 1, 0)]
}
}
my table is 298k rows and although it doesn't take long to execute (below), its part of a long script and I have quite a few inefficient loops so I am trying to get the overall run time down.
Time to run:
user system elapsed
0.99 0.06 1.05
Thanks in advance.
model.matrix()
as well. Perhaps by usage you want something like that. – Ridenhour