Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 替换每个数组元素的矩阵值_Arrays_R_Matrix_Indexing - Fatal编程技术网

Arrays 替换每个数组元素的矩阵值

Arrays 替换每个数组元素的矩阵值,arrays,r,matrix,indexing,Arrays,R,Matrix,Indexing,我有一个三维数组arr,其中每个数组元素都是一个具有相同行数和列数的矩阵。然后我有一个3列矩阵m,其中前两列指定一个索引(行和列),最后一列指定一个值 arr = array(0, dim = c(2, 2, 3)) m = matrix(c(1, 2, -100, 2, 1, -99), ncol = 3, byrow = TRUE) colnames(m) = c("row_index", "column_index", "value") 现在,我想在每个数组元素的指定索引处填充这个值。我

我有一个三维数组
arr
,其中每个数组元素都是一个具有相同行数和列数的矩阵。然后我有一个3列矩阵
m
,其中前两列指定一个索引(行和列),最后一列指定一个值

arr = array(0, dim = c(2, 2, 3))
m = matrix(c(1, 2, -100, 2, 1, -99), ncol = 3, byrow = TRUE)
colnames(m) = c("row_index", "column_index", "value")
现在,我想在每个数组元素的指定索引处填充这个值。我找不到比下面几行代码更好的方法,但我更喜欢代码重复较少的解决方案。最好的方法是什么

arr[, , 1][m[, 1:2]] = m[, 3]
arr[, , 2][m[, 1:2]] = m[, 3]
arr[, , 3][m[, 1:2]] = m[, 3]

这种应用方法怎么样:

arr[] <- apply(arr, 3, FUN = function(x) {x[m[,1:2]] <- m[,3]; x})

arr
# , , 1
# 
# [,1] [,2]
# [1,]    0 -100
# [2,]  -99    0
# 
# , , 2
# 
# [,1] [,2]
# [1,]    0 -100
# [2,]  -99    0
# 
# , , 3
# 
# [,1] [,2]
# [1,]    0 -100
# [2,]  -99    0

arr[]不错。也可以在上述代码中使用
replace
replace(arr,TRUE,apply(arr,3,replace,m[,1:2],m[,3]))
@G.Grothendieck,谢谢。那外装的
replace
非常有趣,太棒了!我尝试了
arr@needRhelp空的
[]
用于保持
arr
的原始结构,如果
idx就好了