Andreas
Andreas

Reputation: 7560

How to vectorize indexing?

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.

Upvotes: 0

Views: 91

Answers (1)

Ali
Ali

Reputation: 9850

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],]))

Upvotes: 2

Related Questions