[英]How to use vector elements as coordinates for matrix positions in r?
I'd like to use elements of a vector that consists strictly of double digit figures as a mapping to specific matrix positions.我想使用严格由两位数组成的向量元素作为到特定矩阵位置的映射。 For instance, consider the following:
例如,请考虑以下内容:
mat1 <- rbind(c(12,31,22,13),c(3,1,5,7))
mat <- matrix(rep( 0, len=25), nrow = 5)
What I'd like to do is use mat1[1,1]
to access position 1 2 of mat
, and at that position, I'd like the corresponding value of 3 to be stored.我想做的是使用
mat1[1,1]
访问 position 1 2 mat
,在那个 position,我想存储 3 的相应值。 I've tried converting mat1's
elements to strings, splitting them, storing them, calling the as.numeric()
function on the vector in which they're stored and finally running a loop, and while I ultimately got it to work, I now have close to a million loops in my program.我试过将
mat1's
元素转换为字符串,拆分它们,存储它们,在存储它们的向量上调用as.numeric()
function 最后运行一个循环,虽然我最终让它工作,但我现在我的程序中有近一百万个循环。 I'd appreciate any ideas!我会很感激任何想法!
We can strsplit
the first row of 'mat', convert it to a row/column index, and use that to assign the corresponding elements of 'mat' with the second rows of 'mat1'我们可以
strsplit
'mat' 的第一行,将其转换为行/列索引,并使用它来将 'mat' 的相应元素分配给 'mat1' 的第二行
i1 <- do.call(rbind, lapply(strsplit(as.character(mat1[1,]),""), as.numeric))
mat[i1] <- mat1[2,]
mat
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 3 7 0 0
#[2,] 0 5 0 0 0
#[3,] 1 0 0 0 0
#[4,] 0 0 0 0 0
#[5,] 0 0 0 0 0
Or with substr
或者用
substr
m1 <- mat1[1,]
i1 <- cbind(as.integer(substr(m1, 1, 1)), as.integer(substr(m1, 2, 2)))
mat[i1] <- mat1[2,]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.