Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operate on pairs of rows of a data frame

Tags:

r

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?

like image 380
Lorin Hochstein Avatar asked Apr 11 '10 03:04

Lorin Hochstein


1 Answers

To calculate the differences, perhaps you could use

outer(df$Score,df$Score,"-")
like image 81
unutbu Avatar answered Oct 23 '22 21:10

unutbu