0

I average coordinates stored in a data frame as follows:

sapply(coords[N:M,],mean) # mean of coordinates N to M

I need the average of several sets of coordinates, so I made this loop, which finds the mean of coordinates 1-4, 5-11 and 20-30.

N <- c(1, 5,20)
M <- c(4,11,30)
for ( i in 1:length(N) ) {
    sapply(coords[N(i):M(i),],mean)
}

How can I vectorize that loop? I've tried to pass a matrix to coords (coords[NM,]), but that doesn't give me what I want.

Andreas
  • 7,470
  • 10
  • 51
  • 73
  • 1
    -1 because this is not [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and because you accepted an answer only half an hour after posting the question [LINK](http://meta.stackexchange.com/a/5236) – GSee Nov 22 '12 at 04:19
  • What is not reproducible? I tried the code before pasting it here. I accepted the answer because it solved my problem. If I get a better one, I always change the accepted answer. – Andreas Nov 22 '12 at 04:26
  • @GSee It could be any numeric data frame with >=30 elements. – Andreas Nov 22 '12 at 04:28

1 Answers1

2

You may replace your sapply(x, mean) by colMeans(x) in the sake of simplicity and efficiency.

Perhaps by a vector thinking you prefer to convert several variables (N and M) to a single vector - here array - when possible and simple.

N <- data.frame(from=c(1,5,20), to=c(4,11,30))
apply(N, 1, function(x) colMeans(coords[x[1]:x[2],]))
Ali
  • 9,440
  • 12
  • 62
  • 92