如果出于某种原因,R工作流程中出现了基础R(二维)table
对象,那么将其转换为{{1}的最佳方式(简洁,易读,高效)是什么? },同时保持其尺寸结构?
示例数据:
data.table
尝试失败的示例
set.seed(1)
tab <- structure(
sample(0:1, size = 15, replace = TRUE),
.Dim = c(5,3),
.Dimnames = list(
Pr = c("P1", "P2", "P3", "P4", "P9"),
Tr = c("T1", "T2", "T3")
),
class = "table"
)
答案 0 :(得分:2)
两种可能的解决方案是使用unclass
(将表转换为规则的2d数组)或使用as.data.frame
的矩阵方法:
# Convert it to a regular array with unclass
data.table(unclass(tab), keep.rownames = "Pr")
# Pr T1 T2 T3
# 1: P1 0 1 0
# 2: P2 0 1 0
# 3: P3 1 1 1
# 4: P4 1 1 0
# 5: P9 0 0 1
# Convert it first to a data.frame
setDT(as.data.frame.matrix(tab), keep.rownames = "Pr")[]
# Pr T1 T2 T3
# 1: P1 0 1 0
# 2: P2 0 1 0
# 3: P3 1 1 1
# 4: P4 1 1 0
# 5: P9 0 0 1