How to modify the values ​​in the original matrices of a function in R?

advertisements

I tried following code:

matrix1 = array(NA, c(3,4))
matrix2 = array(NA, c(3,4))

myfn = function(mat1, mat2){
    for(x in 1:4)   {
        mat1[2,x] = 5
        mat2[2,x] = 6
    }
    cat("MATRICES INSIDE FUNCTION: \n")
    print(mat1)
    print(mat2)
}

myfn(matrix1,matrix2)

matrix1
matrix2

The value of matrices change in the function but the original matrices are not changing. How can I change original matrices from within a function?


You may try:

myfn <- function(mat1, mat2, Ncol, rowIndex) {
vars <- sapply(substitute(list(mat1, mat2)), deparse)[-1]
mat1[rowIndex, 1:Ncol] <- 5
mat2[rowIndex, 1:Ncol] <- 6
lst <- setNames(list(mat1, mat2), vars)
list2env(lst, envir = .GlobalEnv)
}

myfn(matrix1, matrix2, 4, 2)
#<environment: R_GlobalEnv>

 matrix1
    [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]    5    5    5    5
[3,]   NA   NA   NA   NA
matrix2
     [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]    6    6    6    6
[3,]   NA   NA   NA   NA