Cannot dynamically modify external variables in a subroutine in R while use apply on a matix?
This problem has already confused me for a couple of days. Let us say that I have two matrices:
matrix_a <- matrix(0, nrow = 3, ncol = 3,
dimnames = list(c("r1", "r2", "r3"), c("c1", "c2", "c3")))
matrix_b <- matrix(c("r1", "r2", "c1", "c2"), nrow = 2, ncol = 2)
I want to dynamically modify matrix_a
in a function:
change_var <- function(x, matrix_a) {
if(any(rownames(matrix_a) == x[1]) && any(colnames(matrix_a开发者_运维问答) == x[2])) {
matrix_a[x[1], x[2]] <- 1
return (matrix_a)
}
}
apply(matrix_b, 1, change_var, matrix_a)
however, it seems like that this code cannot change the matrix_a
at all. But my intended result of matrix_a
should be
c1 c2 c3
r1 1 0 0
r2 0 2 0
r3 0 0 0
How could we achieve the goal of dynamically modification of the matrix_a
? Please provide me a not-for-loop solution. Thanks in advance.
As you already know, <<-
or assign
can be used to modify a "global" variable. <<-
is very similar to calling assign
with inherits=TRUE
.
...but it seems you're trying to create a matrix which counts the number of occurrences of cell coordinates given by matrix_b? That is more efficiently done (without for loops!) with the table
function. I added a duplicate row in matrix_b
to show that it works:
matrix_a <- matrix(0, nrow = 3, ncol = 3,
dimnames = list(c("r1", "r2", "r3"), c("c1", "c2", "c3")))
matrix_b <- matrix(c("r1", "r2", "r2", "c1", "c2", "c2"), nrow = 3, ncol = 2)
# Convert matrix_b from 2-d to 1-d indices
row <- match(matrix_b[,1], rownames(matrix_a))
col <- match(matrix_b[,2], colnames(matrix_a))
idx <- row+(col-1)*nrow(matrix_a)
# Then count the number of identical indices using table
matrix_a[sort(unique(idx))] <- table(idx)
Which updates matrix_a
to:
c1 c2 c3
r1 1 0 0
r2 0 2 0
r3 0 0 0
...of course, if you only need to put a 1
in there, you don't need to call table
:
row <- match(matrix_b[,1], rownames(matrix_a))
col <- match(matrix_b[,2], colnames(matrix_a))
idx <- row+(col-1)*nrow(matrix_a)
matrix_a[idx] <- 1
精彩评论