问题
I have some vector vect
and I want to iterate over the row vectors v
of a matrix and calculate:
cov(v, vect)
.
I tried:
for(vect in mat2) #where mat2 is a 215 by 31 matrix
However, each vector appeared to be a scalar with value 1.
- How do I iterate over the row vectors of a matrix?
- To make this even better, since I am interested in calculating the sum of
cov(v, vect)
where v is a row vector, how can I use the higher-order functionsleft-fold
andright-fold
回答1:
Are you looking for apply
?
apply(mat2, 1, function(v)cov(v,vect))
回答2:
If I understand that vect is a separate vector from mat2:
apply(mat2, 1, function(v) cov(v, vect))
The apply function allows you to apply an arbitrary function over the rows (if the second argument is 1) or columns (if 2) or a higher dimension (if >2). It is also much faster than using a loop.
来源:https://stackoverflow.com/questions/16005594/r-iterating-over-the-row-vectors-of-a-matrix