r中data.table中的class.ind

r中data.table中的class.ind,r,data.table,R,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 导致: a b c d e 1: 1 1 0 0 4 2: 2 0 1 0 5 3: 3 0 0 1 6 我认为一定有更简单的方法。使用dcast.data.table。您需要一个返回1/0的变量或函数,指示是否存在组合 library(reshape2) # using a variable)

拿这个玩具
数据。表

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
导致:

   a b c d e
1: 1 1 0 0 4
2: 2 0 1 0 5
3: 3 0 0 1 6

我认为一定有更简单的方法。

使用
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
library(重塑2)
#(使用变量)

k_ind刚刚发布了一个
模型.matrix
答案,但这更好。我不懂如何使用“any(x)+0L”,你能解释一下吗。
 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