Created
March 15, 2016 08:17
-
-
Save DoktorMike/8e70cfe71c2864872998 to your computer and use it in GitHub Desktop.
An example of passing matrix by reference in R using the R6 framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(R6) | |
| library(pryr) | |
| # Class defining a storage for a local matrix | |
| LocalMatrix <- R6Class("LocalMatrix", public = list(x = NULL)) | |
| # Class defining a container for a shared matrix | |
| SharedMatrix <- R6Class("SharedMatrix", public = list(e = LocalMatrix$new())) | |
| # Initialize a shared container containing a local matrix and print it | |
| o1 <- SharedMatrix$new() | |
| o1$e$x <- matrix(1, 13, 12) | |
| o1$e$x | |
| # Create a "new" shared matrix and update the local matrix in position 2,3 with the value 5 | |
| o2 <- SharedMatrix$new() | |
| o2$e$x[2:10,3:6]<-5 | |
| # Changing o2$e$x has changed the value of o1$e$x | |
| o1$e$x | |
| # Create a list of a 1000 ShareMatrix | |
| myl<-list() | |
| for(i in 1:1000) myl[[i]]<-SharedMatrix$new() | |
| # See the size | |
| print(paste("Object o1 is of size: ", object_size(o1))) | |
| print(paste("Object o2 is of size: ", object_size(o2))) | |
| print(paste("Object myl is of size: ", object_size(myl))) | |
| print(paste("A list of a 1000 sharedMatrix takes up only: ", object_size(o1)*1000)) | |
| # Timing stuff (around a factor 11 times faster for 1000 replications) | |
| stmp<-SharedMatrix$new() | |
| stmp$e$x<-matrix(1, 500, 100) | |
| system.time({myl<-list(); for(i in 1:1000) myl[[i]]<-SharedMatrix$new()}) | |
| system.time({myl<-list(); for(i in 1:1000) myl[[i]]<-matrix(1, 500, 100)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment