0

我正在尝试从列联/频率表创建一个 9 x 9 概率矩阵。

它包含一对值(x1,x2)转换为一对值的频率(y1,y2)x1并且y1具有、 或的值A,并且具有、、OR的值。BCx2y2DEF

所有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,没有使用factoronx并且y具有正确的值,但当然包括完整的 9x9 转换集。期望的结果DFMd如下。

但是,当我包含factoredxy时,产生的结果是不希望的,引入了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"))
4

1 回答 1

0

我仍然不确定为什么上面的代码会产生一些inf值或错误的值,但下面的代码会产生所需的输出。看起来确实有点绕。

t1 <- with(df,(table(x,y))) # contingency table
tcc <- as.matrix(colSums(t1)) # get col sums
tc <-as.data.frame.matrix(tcc) # store as data.frame to using the rep code below
tct <- t(tc) # transpose to build matrix of colsums
tcx <- tct[rep(seq_len(nrow(tct)), each=9),] # http://stackovernflow.com/a/11121463/1670053 build colsums dataframe to be 9x9

pmat <- t1/tcx # transition matrix
pmat[is.na(pmat)] <- 0 #remove na from 0/0
于 2015-07-25T12:51:57.937 回答