We have multiple typos in the OP's code, i.e. iterate
vs. itreate
and calling medainfunc
while the original function is medianfunc
. In addition, we are providing only a single input value for 'iterate', so seq(iterate
may be we want inside the function. Otherwise, we get a single value output.
medianfunc<-function(n,mu,sigma,iterate){
m<-c()
for (i in seq(iterate)){
x<-rnorm(n,mu,sigma)
y<-median(x)
m<-c(m,y)
}
m
}
set.seed(25)
medianfunc(10,3,15, 5)
#[1] 0.9770646 -6.4852741 4.6768291 -6.4167869 5.3176253
This could be vectorized by getting the rnorm
of 'n*iterate' values. Convert this to a matrix
and use colMedians
from library(matrixStats)
.
medianfunc1 <- function(n, mu, sigma, iterate){
m1 <- matrix(rnorm(n*iterate, mu, sigma), ncol=iterate)
library(matrixStats)
colMedians(m1)
}
set.seed(25)
medianfunc1(10,3,15, 5)
#[1] 0.9770646 -6.4852741 4.6768291 -6.4167869 5.3176253