See Permanent and temporary Objects with R
set.seed(1) # make it reproducible
Creating matrix inside a function:
mat <- function() {
matrix0 <- matrix(rexp(25, rate = 0.1), ncol = 5)
matrix0[1, 1] <- NA
matrix1 <<- na.omit(matrix0)
}
List objects:
ls()
## [1] "mat"
matrix0 doesn't exist outside the function environment, unless created outside that function. Nor does matrix1, despite super-assignment.
Once defined in the global environment it does exist:
matrix0 <- matrix(rexp(25, rate = 0.1), ncol = 5)
matrix0
## [,1] [,2] [,3] [,4] [,5]
## [1,] 7.552 28.950 13.91 10.352 23.645
## [2,] 11.816 12.296 7.62 18.760 6.419
## [3,] 1.457 5.397 12.38 6.547 2.941
## [4,] 1.398 9.566 44.24 3.369 5.659
## [5,] 4.361 1.470 10.55 5.885 1.061
ls()
## [1] "mat" "matrix0"
matrix1 won't exist unless captured as output from the function:
mat <- function(x) {
x[1, 1] <- NA
na.omit(x)
}
matrix1 <- mat(matrix0)
matrix1
## [,1] [,2] [,3] [,4] [,5]
## [1,] 11.816 12.296 7.62 18.760 6.419
## [2,] 1.457 5.397 12.38 6.547 2.941
## [3,] 1.398 9.566 44.24 3.369 5.659
## [4,] 4.361 1.470 10.55 5.885 1.061
## attr(,"na.action")
## [1] 1
## attr(,"class")
## [1] "omit"
identical(matrix0, matrix1) # true/false
## [1] FALSE
all.equal(matrix0, matrix1) # comparison
## [1] "Attributes: < Length mismatch: comparison on first 1 components >"
## [2] "Attributes: < Component \"dim\": Mean relative difference: 0.2 >"
## [3] "Numeric: lengths (25, 20) differ"
Or creating matrix0 inside the function:
remove(matrix0) # remove existing object
mat2 <- function(n, rate = 1, ncol) {
set.seed(1)
x <- matrix(rexp(n, rate), ncol)
x[1, 1] <- NA
na.omit(x)
}
matrix1 <- mat2(n = 25, rate = 0.1, ncol = 5)
matrix1
## [,1] [,2] [,3] [,4] [,5]
## [1,] 11.816 12.296 7.62 18.760 6.419
## [2,] 1.457 5.397 12.38 6.547 2.941
## [3,] 1.398 9.566 44.24 3.369 5.659
## [4,] 4.361 1.470 10.55 5.885 1.061
## attr(,"na.action")
## [1] 1
## attr(,"class")
## [1] "omit"
ls()
## [1] "mat" "mat2" "matrix1"