使用 presence/absence 调用作为值将 R 数据帧转换为宽格式

convert R data frame to wide format with presence/absence call as value

我有一个如下所示的数据框:

ID  cat1  cat2  cat3
1  cat1_A  cat2_A  cat3_A
2  cat1_B  cat2_A  cat3_B
3  cat1_B  cat2_B  cat3_A

我现在想将其转换为一种转置 table,使用每列中的所有值作为新列名,并为相应列调用 0/1 (presence/absence)名称作为新值:

ID cat1_A cat1_B cat2_A cat2_B cat3_A cat3_B
1 1 0 1 0 1 0
2 0 1 1 0 0 1
3 0 1 0 1 1 0

我希望清楚我想做什么,但不确定如何以更好的方式解释它。任何帮助将不胜感激! 谢谢!

我们可以使用 mtabulate 来自 qdapTools

res <- cbind(df1[1], mtabulate(as.data.frame(t(df1[-1]))))
row.names(res) <- NULL
res
#   ID cat1_A cat2_A cat3_A cat1_B cat3_B cat2_B
#1  1      1      1      1      0      0      0
#2  2      0      1      0      1      1      0
#3  3      0      0      1      1      0      1