Operation with a column vector without using a loop in R

Viewed 27

I want to perform an operation over a vector without using a loop. The operation is the following: enter image description here

This is how I am coding in R

  meanx <- mean(rankx)
  Numerador <- (rankx[] - meanx)*(rankx[+1] - meanx)

This is the input:

> dput(rankx)
c(15, 11, 12, 30, 58, 14, 41, 10, 57, 32, 28, 52, 61, 18, 54, 
37, 19, 7, 29, 66, 5, 47, 25, 6, 50, 65, 62, 23, 40, 63, 42, 
64, 38, 56, 45, 17, 8, 59, 55, 67, 24, 60, 2, 35, 44, 20, 3, 
39, 4, 31, 26, 51, 21, 22, 53, 33, 46, 9, 16, 36, 13, 27, 34, 
48, 1, 49, 43)

For example for the first case it will be: (15 - mean(rankx))(11 - mean(rankx)) For the next: (11 - mean(rankx))(12 - mean(rankx))

I am not sure how to refer to the second element and my error is in rankx[+1]

Any idea in how to solve this operation without using a loop?

1 Answers

You can use dplyr::lead

rankx[+1] is equivalent to rankx[1], which is 15.

If you want a copy of rankx that's displaced by one unit, use dplyr::lead(rankx) - like this:

rankx <- c(15, 11, 12, 30, 58, 14, 41)

dplyr::lead(rankx)
#> [1] 11 12 30 58 14 41 NA

meanx <- mean(rankx)
Numerador <- (rankx - meanx)*(dplyr::lead(rankx) - meanx)

Numerador
#> [1]  161.30612  205.87755  -57.40816  133.16327 -381.12245 -179.55102         NA

Created on 2021-04-20 by the reprex package (v1.0.0)

Related