James Vrtis
James Vrtis

Reputation: 21

Creating a Vector from a Loop in R

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]

Upvotes: 2

Views: 52

Answers (1)

John Coleman
John Coleman

Reputation: 52008

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

Upvotes: 3

Related Questions