R, iterating over the row vectors of a matrix

我怕爱的太早我们不能终老 提交于 2020-01-14 14:59:31

问题


I have some vector vect and I want to iterate over the row vectors vof 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.

  1. How do I iterate over the row vectors of a matrix?
  2. 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 functions left-fold and right-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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!