Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorised way to calculate mean of left and right neighbours in a vector

Tags:

r

I have a vector

x = c(1820.0, 2235.0, 2534.0, 2580.0, 2322.0, 2317.0, 2331.0, 2345.0, 
      2305.0, 2265.0, 2277.0, 2289.0, 2338.0, 2387.0, 2152.0, 2256.0, 
      2360.0, 2590.0, 2529.0, 2468.0, 2776.0, 2909.0, 3017.0, 3081.0,
      3118.5, 3156.0, 3338.0, 3211.5)

I want to calculate the mean of left and right neighbors of each element except edges. For example, the result should be like this : mean(1820,2534), mean(2235,2580), mean(2534,2322) ...

I am able to do this using loops but that is very slow. I need a vectorized solution.

My code using a for loop:

neighbour_m = function(x) {
  newx = c(x[length(x)], x, x[1])
  for (i in 2:(length(newx) - 1)){
    m = mean(c(newx[i-1], newx[i+1]))
  }
}
like image 797
gis.rajan Avatar asked Aug 05 '19 09:08

gis.rajan


People also ask

How to take mean of a vector in R?

The mean is calculated by taking a sum of the values and dividing by the number of values in the data. If the data series is a vector, the mean is calculated by taking a sum of vector elements and dividing by the number of elements of the series. To calculate the mean in R, use an inbuilt mean() function.

How to calculate mean of numeric vector in R?

It is calculated by taking the sum of the values and dividing with the number of values in a data series. The function mean() is used to calculate this in R.

How to find the average value of a vector in R?

To calculate the average in R, use the mean() function. The average is calculated by taking a sum of the input values and dividing by the number of values in the input data. The Mean is the sum of its data values divided by the count of the data.


1 Answers

Another base R option using rowMeans and cbind

rowMeans(cbind(x[1:(length(x) - 2)], x[3:(length(x))]))
# [1] 2177.00 2407.50 2428.00 2448.50 2326.50 2331.00 2318.00 2305.00 2291.00
#[10] 2277.00 2307.50 2338.00 2245.00 2321.50 2256.00 2423.00 2444.50 2529.00
#[19] 2652.50 2688.50 2896.50 2995.00 3067.75 3118.50 3228.25 3183.75
like image 87
Maurits Evers Avatar answered Oct 13 '22 13:10

Maurits Evers