2016-10-24 158 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 
相關問題