我正在尝试从列联/频率表创建一个 9 x 9 概率矩阵。
它包含一对值(x1,x2)
转换为一对值的频率(y1,y2)
。x1
并且y1
具有、 或的值A
,并且具有、、OR的值。B
C
x2
y2
D
E
F
所有xy
对之间的转换都不存在。但是,我希望这些“缺失”的转换在表格/矩阵中以零的形式出现,以使其成为方形 (9x9) 以用于其他分析。
df <- structure(list(x1 = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L, 1L, 2L, 3L), .Label = c("A", "B", "C"), class = "factor"),
y1 = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L), .Label = c("A", "B", "C"), class = "factor"),
x2 = structure(c(1L,2L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 1L),
.Label = c("D", "E", "F"), class = "factor"),
y2 = structure(c(1L, 2L, 3L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 3L),
.Label = c("D", "E", "F"), class = "factor"),
x = c("AD", "BE", "CF", "AD", "BD", "CD", "AE", "BE", "CE", "AE", "BF", "CD"),
y = c("AD", "BE", "CF", "AE", "BD", "CD", "AD", "BD", "CD", "AE", "BE", "CF")),
.Names = c("x1", "y1", "x2", "y2", "x", "y"), row.names = c(NA, -12L), class = "data.frame")
# df$x <- paste0(df$x1, df$x2) # included in the dput
# df$y <- paste0(df$y1,df$y2)
# convert to factor to include all transitions http://stackoverflow.com/a/13705236/1670053
df$x <- factor(df$x, levels = c("AD", "AE", "AF", "BD", "BE", "BF", "CD", "CE", "CF"))
df$y <- factor(df$y,levels = c("AD", "AE", "AF", "BD", "BE", "BF", "CD", "CE", "CF") )
t1 <- with(df,(table(x,y)))
# t1m <- as.data.frame.matrix(t1)
t2 <- t1/(colSums(t1))
dfm <- as.data.frame.matrix(t2)
#dm <- as.matrix(dfm)
上面的结果DFM
,没有使用factor
onx
并且y
具有正确的值,但当然包括完整的 9x9 转换集。期望的结果DFMd
如下。
但是,当我包含factor
edx
和y
时,产生的结果是不希望的,引入了NA
和的值。Inf
有没有办法使用“缺失”因素来评估table/colSums(table)
并获得所需的结果?
DFMd <- structure(list(AD = c(0.5, 0.5, 0, 0, 0, 0, 0, 0, 0), AE = c(0.5,
0.5, 0, 0, 0, 0, 0, 0, 0), AF = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L), BD = c(0, 0, 0, 0.5, 0.5, 0, 0, 0, 0), BE = c(0, 0,
0, 0, 0.5, 0.5, 0, 0, 0), BF = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L), CD = c(0, 0, 0, 0, 0, 0, 0.5, 0.5, 0), CE = c(0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L), CF = c(0, 0, 0, 0, 0, 0, 0.5, 0,
0.5)), .Names = c("AD", "AE", "AF", "BD", "BE", "BF", "CD", "CE",
"CF"), class = "data.frame", row.names = c("AD", "AE", "AF",
"BD", "BE", "BF", "CD", "CE", "CF"))