Dani
Dani

Reputation: 163

Create functions for statistic median

I'm trying to write a function to find medians using the loop "for". At this moment, this is my function:

mediana <- function (x,k=3){
  n<-length(x)
  r_med <- NULL
  m <- matrix(x,n,k)
  for (i in k){
    r_med[i]<-apply(m,1,median)[1:(n-k+1)]
  }
}

But when I try to probe the function, this warning message appears:

Warning message:
In r_med[i] <- apply(m, 1, median)[1:(n - k + 1)] :
  number of items to replace is not a multiple of replacement length

Can anyone help me with my problem? I'm beginner in R and I'm suffering a lot to understand the programming!

Thanks!

Upvotes: 0

Views: 116

Answers (1)

cdeterman
cdeterman

Reputation: 19960

If you are just trying to find a function, use rollapply as Roland suggests. If you are trying to teach yourself some programming continue reading.

If I understand correctly, by 'running median' you mean take the median of every k elements. For example:

> runif(9)
[1] 0.5889687801 0.9012693244 0.9394947358 0.3996177884 0.9639447967 0.7152831559 0.1913678751 0.7477577361 0.5264336797

If k=3 the first median would of 0.589, 0.901, & 0.939, the second 0.901, 0.939, & 0.399, etc.

If so, you don't need the apply or matrix statements as you can index a vector.

The revised function would look like this:

mediana <- function (x,k=3){
  n<-length(x)
  r_med <- vector("numeric", n-k+1)
  for (i in seq(n-k+1)){
    r_med[i] <- median(x[i:(i+k-1)])
  }
  return(r_med)
}

A few programming points:

  1. Your loop needs something to iterate over, either something like 1:k or using seq. The number of combinations will be n-k+1 so you use that.
  2. As noted in the comments by Roland, you shouldn't grow objects in loops. Specify the size of the object you are filling (e.g. vector("numeric", n-k+1))
  3. Although somewhat stylistic, it is good form to provide a return statement. In a simple function like this it isn't as much of an issue but good for clarity.

Upvotes: 1

Related Questions