我正在尝试填充矩阵,以便每个元素都是由其坐标(行,列)组成的字符串。
即
[ '1,1' '1,2' '1,3' ]
[ '2,1' '2,2' '2,3' ]
[ '3,1' '3,2' '3,3' ]
我已经能够用方形矩阵做到这一点,但如果我改变行数或列数,它就不健壮。
这是我到目前为止所拥有的
#Works but only with a square matrix
x <- 20 #Number of rows
y <- 20 #Number of columns
samp <- 200 #Number of frames to sample
grid = matrix(data = NA,nrow = x,ncol = y)
for (iter_col in 1:y){
for (iter_row in 1:x){
grid[iter_col,iter_row] = paste(toString(iter_row),toString(iter_col),sep = ',')
}
}
我正在使用它来随机采样网格,我将其叠加在图像上以进行细胞计数方法。所以我还没有任何数据。并非所有这些网格都具有相同数量的行和列。
你能帮助我提高灵活性吗?我在R的背景有点缺乏,所以解决方案就在我面前......
谢谢!
修改
我grid[iter_col,iter_row]
中的变量排序错误。切换后,它适用于不同尺寸的矩阵。
感谢G5W捕获该错误。
答案 0 :(得分:1)
这是使用sapply
rows = 4
columns = 5
sapply(1:columns, function(i) sapply(1:rows, function(j) paste(j,i,sep = ", ")))
# [,1] [,2] [,3] [,4] [,5]
#[1,] "1, 1" "1, 2" "1, 3" "1, 4" "1, 5"
#[2,] "2, 1" "2, 2" "2, 3" "2, 4" "2, 5"
#[3,] "3, 1" "3, 2" "3, 3" "3, 4" "3, 5"
#[4,] "4, 1" "4, 2" "4, 3" "4, 4" "4, 5"
答案 1 :(得分:1)
我怀疑这会快得多:
matrix(paste0(rep(seq_len(x), times=y), ", ", rep(seq_len(y), each=x)), nrow = x, ncol = y)
[,1] [,2] [,3] [,4] [,5]
[1,] "1, 1" "1, 2" "1, 3" "1, 4" "1, 5"
[2,] "2, 1" "2, 2" "2, 3" "2, 4" "2, 5"
[3,] "3, 1" "3, 2" "3, 3" "3, 4" "3, 5"
[4,] "4, 1" "4, 2" "4, 3" "4, 4" "4, 5"
或使用col
和row
(如@rawr的评论中所述)
grid[] <- paste0(row(grid), ", ", col(grid))