2016-10-24 122 views
0

我有一个有11217行和2列的矩阵1,第二个矩阵2有10行和10列。现在,我想比较矩阵1行中的值和矩阵2的索引,如果它们相同,那么矩阵2的相应索引(当前为0)的值应该增加+1。将矩阵的同一行的2个值与另一个矩阵的行和列索引相比较R

 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

你可能要替换'M2 [最后一行r,c] = m2 [r,c] + 1' – etienne

回答

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 
相关问题