我有一个11217行和2列的matrix1,第二个matrix2有10行10列。现在,我想比较矩阵1的行中的值与矩阵2的索引,如果它们相同,那么矩阵2的相应索引(当前为0)的值应该增加+1。
c1 <- x[2:11218] #these values go from 1 to 10
#second column from index 3 to N
c2 <- x[3:11219] #these values also go from 1 to 10
#matrix with column c1 and c2
m1 <- as.matrix(cbind(c1 = c1, c2 = c2))
#empty matrix which will count the frequencies
m2 <- matrix(0, nrow = 10, ncol = 10)
#change row and column names of m2 to the numbers of 1 to 10
dimnames(m2) <-list(c(1:10), c(1:10))
#go through every row of the matrix m1 and look which rotation appears, add 1 to m2 if the rotation
#equals the corresponding index
r <- c(1:10)
c <- c(1:10)
for (i in 1:nrow(m1)) {
if(m1[i,1] == r & m1[i,2] == c)
m2[r,c]+1
}
没有计算的频率,我不明白为什么?
答案 0 :(得分:0)
您似乎正在尝试复制table
的行为。我建议只使用它。
更简单的数据(看起来你没有包含变量x
):
m1 <-
matrix(round(runif(20, 1,10))
, ncol = 2)
然后,使用table
。在这里,我将每列的值设置为一个因子,以确保生成正确的列:
table(factor(m1[,1], 1:10)
, factor(m1[,2], 1:10))
给出:
1 2 3 4 5 6 7 8 9 10
1 3 4 0 4 2 0 5 3 2 0
2 3 7 9 7 4 5 3 4 5 2
3 4 6 3 10 8 9 4 2 7 3
4 5 2 14 3 7 13 8 11 3 3
5 2 13 2 5 8 5 7 7 8 6
6 1 10 7 4 5 6 8 5 8 5
7 3 3 6 5 4 5 4 8 7 7
8 5 5 8 7 6 10 5 4 3 4
9 2 5 8 4 7 4 4 6 4 2
10 3 1 2 3 3 5 3 5 1 0