Onur
Onur

Reputation: 35

loop though a matrix in R

I try to loop trough a matrix but cant find a easy and elegant way instead of writing many (>10) equations... Can anyone help me please?

My Matrix looks like this:

enter image description here

and I want to calculate the following:

(0 * 0 * 4/24) + (0 * 1 * 6/24) + (0 * 2 * 3/24) + (1 * 0 * 3/24) + (1 * 1 * 4/24) + (1 * 2 * 4/24)

instead of using

__ btw: my code for the matrix

vals<- c(4/24, 6/24, 3/24, 3/24, 4/24, 4/24)
x <- c(0,1)
y <- c(0,1,2)
df <- matrix(vals, byrow = TRUE, nrow = 2, ncol = 3,
             dimnames = list(x,y))

instead of calculation each step manually, I think there should be a for-loop method, but cant figure it out..

Upvotes: 1

Views: 107

Answers (4)

PaulS
PaulS

Reputation: 25323

A possible solution:

c(x %*% df %*% y) 

#> [1] 0.5

Another possible solution, based on outer:

sum(outer(x, y, Vectorize(\(x,y) x*y*df[x+1,y+1])))

#> [1] 0.5

Upvotes: 6

WhatIf
WhatIf

Reputation: 636

If you are new to R (as I am), here is the loop approach.

result = 0
for (i in 1:length(x)) {
  for (j in 1:length(y)) {
    result = result + x[i] * y[j] * df[i, j]
  }
}
result

Upvotes: 1

objectclosure
objectclosure

Reputation: 58

sum((x %o% y) * df)

Explanation:

x %o% y gets the outer product of vectors x and y which is:

#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    1    2

Since that has the same dimensions as df, you can multiply the corresponding elements and get the sum: sum((x %o% y) * df)

Upvotes: 2

Zheyuan Li
Zheyuan Li

Reputation: 73295

x <- c(0, 1)
y <- c(0, 1, 2)
vals<- c(4/24, 6/24, 3/24, 3/24, 4/24, 4/24)
mat <- matrix(vals, byrow = TRUE, nrow = 2, ncol = 3,
              dimnames = list(x,y))  ## not a data frame; don't call it "df"

There is even a better way than a for loop:

sum(tcrossprod(x, y) * mat)
#[1] 0.5

Upvotes: 4

Related Questions