Operate on pairs of rows of a data frame

Posted by lorin on Stack Overflow See other posts from Stack Overflow or by lorin
Published on 2010-04-11T03:05:37Z Indexed on 2010/04/11 3:13 UTC
Read the original article Hit count: 259

Filed under:

I've got a data frame in R, and I'd like to perform a calculation on all pairs of rows. Is there a simpler way to do this than using a nested for loop?

To make this concrete, consider a data frame with ten rows, and I want to calculate the difference of scores between all (45) possible pairs.

> data.frame(ID=1:10,Score=4*10:1)
   ID Score
1   1    40
2   2    36
3   3    32
4   4    28
5   5    24
6   6    20
7   7    16
8   8    12
9   9     8
10 10     4

I know I could do this calculation with a nested for loop, but is there a better (more R-ish) way to do it?

© Stack Overflow or respective owner

Related posts about r