R: for循环在矩阵上只返回最后的值



所以我有一个充满随机数的矩阵:mat_base = matrix(sample(1:20, 100, replace = TRUE), nrow=10, ncol=10)和另一个矩阵mat_table = matrix(,100,3),它有列名:colnames(mat_table) <- c("row", "col", "value")

我想把所有的值和它们的位置(行和列号)从mat_basemat_table,我已经成功地做到了这些位置。但是对于每个单元格的值,mat_table只返回mat_base最后一列的值。

这是我到目前为止的代码:

for (j in 1:nrow(mat_base)) {
for (k in 1:ncol(mat_base)){ 
#2 nested for-loops to go through mat_base

mat_table[,1] <- row(mat_base)
#the function "row" returns a matrix of row numbers
#put row numbers in the first column of mat_table

mat_table[,2] <- col(mat_base)
#the function "col" returns a matrix of column numbers
#put column numbers in the second column of mat_table

mat_table[,3] <- mat_base[,k]
#get current value of mat_base and put it into mat_table
#put values in the third column of mat_table
}

}
mat_table
#show mat_table in the console

我知道我可能不需要j的外部for循环,因为没有它的结果是一样的(我不使用j),但我不确定,所以我现在把它留在了。

这是我用这段代码得到的结果:

> mat_table
row col value
[1,]   1   1     4
[2,]   2   1    11
[3,]   3   1    13
[4,]   4   1    13
[5,]   5   1     2
[6,]   6   1    17
[7,]   7   1     7
[8,]   8   1    14
[9,]   9   1    19
[10,]  10   1     3
[11,]   1   2     4
[12,]   2   2    11
[13,]   3   2    13
[14,]   4   2    13
[15,]   5   2     2
[16,]   6   2    17
[17,]   7   2     7
[18,]   8   2    14
[19,]   9   2    19
[20,]  10   2     3
[21,]   1   3     4
[22,]   2   3    11
[23,]   3   3    13
...

可以看到,在mat_table的第三列中,只有mat_base的最后一列反复出现。如何将mat_base中的所有值转换为mat_table?

编辑/答:好吧,我发现通过使用循环,我的生活变得更加艰难……下面是我最后解决这个问题的方法:

mat_base = matrix(sample(1:20, 100, replace = TRUE), nrow=10, ncol=10) 
#my data
mat_table = matrix(,100,3)
#create an empty matrix with 100 rows and 3 columns
colnames(mat_table) <- c("row", "col", "value")
#change the column names 
mat_table <- cbind(c(row(mat_base)), c(col(mat_base)), c(mat_base))
#put row numbers, column numbers and values from mat_base into mat_table
mat_table
#show mat_table in console

编辑2:但如果你想按照我最初尝试的方式来做,看看@Mohanasundaram的答案吧!

获取所需表的另一种方法是:

mat_base = matrix(sample(1:20, 100, replace = TRUE), nrow=10, ncol=10)
mat_table <- data.frame(row = rep(1:nrow(mat_base), by = ncol(mat_base)),
col = rep(1:ncol(mat_base), each = nrow(mat_base)),
value = c(mat_base))

对于您的原始方法,这是解决方案。您必须根据行名和列名筛选矩阵,然后分配值。然而,这不是一种有效的方法。

mat_base = matrix(sample(1:20, 100, replace = TRUE), nrow=10, ncol=10)
mat_table = matrix(,100,3)
colnames(mat_table) <- c("row", "col", "value")
for (j in 1:nrow(mat_base)) {
for (k in 1:ncol(mat_base)){ 
#2 nested for-loops to go through mat_base

mat_table[,1] <- row(mat_base)
#the function "row" returns a matrix of row numbers
#put row numbers in the first column of mat_table

mat_table[,2] <- col(mat_base)
#the function "col" returns a matrix of column numbers
#put column numbers in the second column of mat_table

mat_table[mat_table[,"row"] == j & mat_table[,"col"] == k,3] <- mat_base[j,k]
#get current value of mat_base and put it into mat_table
#put values in the third column of mat_table

}

}

最新更新