Reputation: 571
I am trying to repeatedly compute the median of a random vector, constructing a vector of all the medians. Why do I get a NULL
result from my code below, in which I repeatedly compute the median and add it to the end of the vector m
?
medainfunc<-function(n,mu,sigma,iterate){
m<-c()
for (i in itreate){
x<-rnorm(n,mu,sigma)
y<-median(x)
m<-c(m,y)
}
m
}
medianfunc(10,3,15,10000)
NULL
Upvotes: 0
Views: 74
Reputation: 44299
Building a vector one-by-one is both inefficient (see the second circle of the R inferno) and code-intensive. Instead, you can repeat a randomized operation a certain number of times in a single line of code with the replicate
function:
medianfunc <- function(n, mu, sigma, iterate) {
replicate(iterate, median(rnorm(n, mu, sigma)))
}
set.seed(25)
medianfunc(10,3,15, 5)
# [1] 0.9770646 -6.4852741 4.6768291 -6.4167869 5.3176253
Upvotes: 2
Reputation: 886938
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
Upvotes: 3
Reputation: 1596
I dont know if this is just the code you wrote on the post but the function is called medainfunc
and then on your code you are calling the medianfunc
. That might be just one error, the other thing I noticed is that you should add return
at the end of your function like so:
medainfunc<-function(n,mu,sigma,iterate){
m<-c()
for (i in itreate){
x<-rnorm(n,mu,sigma)
y<-median(x)
m<-c(m,y)
}
return(m)
}
Upvotes: 0