Assignment 2b Advanced Programming in R: Ika Pratiwi
Assignment 2b Advanced Programming in R: Ika Pratiwi
Advanced Programming in R
Ika Pratiwi
Run and describe what the code below does.
#include package parallel on library
>library(parallel)
#assign value of cores by get the number of CPU cores
>cores <- detectCores()
>cores
[1] 4
#assign value of cl by create a set of copies of cores
> cl<-makeCluster(cores)
>cl
socket cluster with 4 nodes on host localhost
#assign value of mat which is matrix of value generated by rnorm() function and have 16 column
#rnorm () function is random generation for the normal distribution, with number of observations equal to 160
mat<-matrix(rnorm(160),ncol=16)
>mat
Run and describe what the code below does.
#assign value of splt by splitting the cluster of cl with sequence 1 until the number of dimension of mat
#which is column
splt<-clusterSplit(cl, 1:dim(mat)[2])
#assign value of spltdat which is generated by lapply() function
#lapply() function returns a list with same length as splt by applying function(i)
#function (i) returns the value of all column of mat
spltdat<-lapply(splt, function(i) mat[,i])
Run and describe what the code below does.
#assign value of res by generated function clusterApply()
#function clusterApply() applies function colMeans to component spltdat on every cluster cl
#function colMeans determine the means of each column
res<-clusterApply(cl, spltdat,colMeans)
#assign value of totout by generated function do.call()
#do.call() function execute function call c with argument res to be passed
#c is a function to combine value res into a vector
totout<-do.call(c,res)
#shutdown the cluster cl
stopCluster(cl)
Try to find an alternative function that performs
the same operation
#include package doSNOW and foreach
library(doSNOW)
library(foreach)
#get the number of CPU cores
cores <- detectCores()
#assign value of cl by create a set of copies of cores
cls<-makeCluster(cores)
#register the SNOW(Simple Network Of Workstations) parallel backend with the foreach package
#cls is a cluster object to use for parallel execution
registerDoSNOW(cls)
#assign value of mat is matrix of value generated by rnorm() function and have 16 column
mat<-matrix(rnorm(160),ncol=16)
#foreach object from 1 until number of column of mat
#the result will be generated with c function
#%dopar% evaluates the function mean of each column of mat in parallel
foreach(i=1:ncol(mat), .combine=c) %dopar% (mean(mat[,i]))
Thank you