NSAA
NSAA

Reputation: 185

Save as vector from For Loop in R

I have a very simple question here. I have been trying to save my results from the loop as a vector. Below is my reproducible code:-

a = matrix( c(0.7, 0.3, 0.2, 0.8),nrow=2, ncol=2, byrow = TRUE)
b = matrix( c(0.02, 0.45, 0.15, 0.30),nrow=2, ncol=2, byrow = TRUE)

d = 0
myvector <- c()

for (i in 1:2) {
    d = d + (a[, i] * b[, i]) 
    myvector[i] <- d
}

myvector
[1] 0.014 0.149

Why it did not give me the whole vector? It only give me the answer for the first row. How do we store the result from the loop as vector?

Upvotes: 0

Views: 145

Answers (1)

Wyldsoul
Wyldsoul

Reputation: 1553

Try this:

a  = matrix( c(0.7, 0.3, 0.2, 0.8),nrow=2, ncol=2, byrow = TRUE)
b   = matrix( c(0.02, 0.45, 0.15, 0.30),nrow=2, ncol=2, byrow = TRUE)
d = 0
myvector <- vector()
for (i in 1:2){
 d = d + (a[,i] * b[,i]) 
myvector <- c(myvector, d)
}

Upvotes: 1

Related Questions