R: How can I convert an ordered factor to dummy variables? -


for example. factor ordered levels

[1] 0 0 6 6 3 4 levels: 0 < 1 < 2 < 3 < 4 < 5 < 6

should converted

ti0 ti1 ti2 ti3 ti4 ti5 ti6 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0

i have looked @ packages dummies , functions model model.matrix cant solution.

this appears work.

x <- factor(c("0", "0", "6", "6", "3", "4"), levels = 0:6, ordered = true)  out <- matrix(0, nrow = length(x), ncol = max(as.numeric(x)))  (i in 1:length(x)) {   out[i, 1:as.numeric(x[i])] <- 1 } colnames(out) <- paste("ti", levels(x), sep = "")        ti0 ti1 ti2 ti3 ti4 ti5 ti6 [1,]   1   0   0   0   0   0   0 [2,]   1   0   0   0   0   0   0 [3,]   1   1   1   1   1   1   1 [4,]   1   1   1   1   1   1   1 [5,]   1   1   1   1   0   0   0 [6,]   1   1   1   1   1   0   0 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -