拿这个玩具data.table
:
dt <- data.table(a=1:3,k=letters[2:4],e=4:6)
a k e
1: 1 b 4
2: 2 c 5
3: 3 d 6
我想将变量“k”转换为dummy(k)
我可以这样做,
dt[,class.ind(k)]
cbind(dt[,1,with=FALSE],dt[,class.ind(k)],dt[,3,with=FALSE])
导致:
a b c d e
1: 1 1 0 0 4
2: 2 0 1 0 5
3: 3 0 0 1 6
我认为必须有一种更简单的方法。
答案 0 :(得分:2)
使用dcast.data.table
。您需要一个返回1/0的变量或函数,指示是否存在组合。
library(reshape2)
# using a variable)
k_ind <- dcast.data.table(dt[,.N,by=names(dt)], a+e~k,fill=0L)
k_ind
# a e b c d
# 1: 1 4 1 0 0
# 2: 2 5 0 1 0
# 3: 3 6 0 0 1
# using a function
k_ind2 <- dcast.data.table(a+e ~ k, data=dt, fun=function(x) any(length(x))+0L)
# you can change the column order using setcolorder
setcolorder(k_ind, c('a',unique(dt[['k']]),'e'))
k_ind
# a b c d e
# 1: 1 1 0 0 4
# 2: 2 0 1 0 5
# 3: 3 0 0 1 6