0

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
josliber
  • 43,891
  • 12
  • 98
  • 133
clarkson
  • 561
  • 2
  • 16
  • 32
  • Check [here](http://stackoverflow.com/questions/32366694/adding-values-to-the-vector-inside-for-loop-in-r). Also try with `for(i in seq(iterate))` Check the typo in `iterate` and `itreate` and `medainfunc` and `medianfunc` as well. – akrun Sep 03 '15 at 05:36

3 Answers3

3

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
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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
josliber
  • 43,891
  • 12
  • 98
  • 133
0

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)
   }
Diego Aguado
  • 1,604
  • 18
  • 36