使用NA将表转换为共现矩阵

时间:2019-07-03 16:13:14

标签: r matrix transformation

我已经简化了R中具有以下结构的表:

id coder evaluation
1  1     1
2  1     2
3  1     1
1  2     1
2  2     2
3  2     3
4  2     3
2  3     3
3  3     3
4  3     3
1  4     1
2  4     2
4  4     1

我的目标是创建以下矩阵:

     [,1] [,2] [,3] [,4]
[1,]    1    2    1    NA
[2,]    1    2    3    3
[3,]   NA    3    3    3
[4,]    1    2    NA   1

我需要使用矩阵作为输入来评估IRR包中评估者之间的可靠性。我试图通过t()进行转置,但是我觉得我需要像枢轴表这样的东西来处理NA。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

x <- read.table(header=TRUE, text="id coder evaluation
1  1     1
2  1     2
3  1     1
1  2     1
2  2     2
3  2     3
4  2     3
2  3     3
3  3     3
4  3     3
1  4     1
2  4     2
4  4     1")

y <- matrix(NA, ncol=max(x$id), nrow=max(x$coder)) #Create empty matrix where ncol are taken from maximum of column id, and nrow from maximum of column coder
y[as.matrix(x[,2:1])] <- x[,3] #Fill the matix, where the positions are taken from x[,2:1] and the values come from x[,3]
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    1   NA
#[2,]    1    2    3    3
#[3,]   NA    3    3    3
#[4,]    1    2   NA    1