Reputation: 1207
I have another problem in R. I need to combine four vectors into one vector. Imagine four vectors of the same length, and I wish to combine like: first element of vector a multiply by first element of vector b plus first element of vector c multiply by first element of vector d.
Here is what I have tried:
x<-rep(5,5)
a<-seq(1,5,1)
c<-rep(1,5)
d<-rep(2,5)
div<-NULL
for(i in 1:5){
div[i]<-x[i]*a[i]+c[i]*d[i]
div<-rbind(div[i])
}
div
[,1]
[1,] 27
I really think that the outcome of this loop should be a vector, but my outcome is just a number. What am I doing wrong?
Upvotes: 2
Views: 209
Reputation:
Yes, div<-rbind(div[i])
is wrong, should not have been there at all because it overwrites all your previously computed data. If you remove it, the result will probably be correct, but you can instead just perform a vectorized operation and not need a loop, like this:
div <- a * x + c * d
This will perform the computation on each set of values of those 4 vectors; the result will a new vector with what you wanted to accomplish as a result.
Upvotes: 2