Cannot dynamically modify external variables in a subroutine in R while use apply on a matix? -
this problem has confused me couple of days. let have 2 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 dynamically modify matrix_a in 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, seems code cannot change matrix_a @ all. intended result of matrix_a should
c1 c2 c3 r1 1 0 0 r2 0 2 0 r3 0 0 0 how achieve goal of dynamically modification of matrix_a? please provide me not-for-loop solution. in advance.
as know, <<- or assign can used modify "global" variable. <<- similar calling assign inherits=true.
...but seems you're trying create matrix counts number of occurrences of cell coordinates given matrix_b? more efficiently done (without loops!) table function. added duplicate row in matrix_b show 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 2-d 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) # count 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 need put 1 in there, don't need 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
Comments
Post a Comment