2

enter image description here enter image description here

Hello, I am entirely new to using R and experiencing some problems trying to develop the attached equation. Provided below is the general idea of what I am trying to code where PMU1 = omega and PMU2 = omega' from the images.

I am running into two problems that I see which is that Vh[i] is out of bounds for "i+1" when i = 7, and that I can't get a vector solution. The answer for evaluating the above omega matrix is Vh[i] = (0.25,0.25,0,0,0.5,0). I'll eventually be using a different matrix set, but I am just trying to generate a code from the equation.

PMU1 <- as.matrix(PMU1)
PMU2 <- as.matrix(PMU2)

m <- nrow(PMU1)
n <- ncol(PMU1)

for (j in 1:n)
  {
 Vh[i] <- sum(abs(PMU1[i,j]-PMU1[i+1,j]))
  }

Vh[i]
  • 2
    Please improve your question by more specifically describing what you are trying to achieve. Also share the code you have tried so far. – Till Mar 05 '22 at 19:18
  • This isn't a homework question. – James Vrtis Mar 05 '22 at 19:34
  • 1
    Your edit helps, but it still isn't a [mcve]. See [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269/4996248) for some helpful tips in making a reproducible example. – John Coleman Mar 05 '22 at 19:51

1 Answers1

3

While a more vectorized approach probably exists, a simple approach is to use sapply:

PMU <- matrix(c(0,1,1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1),nrow = 7)
V <- sapply(1:(nrow(PMU)-1),function(i)mean(PMU[i+1,]-PMU[i,]))

After running this code, V = 0.25 0.25 0.00 0.00 0.50 0.00

John Coleman
  • 51,337
  • 7
  • 54
  • 119