我在R中有一个数据框,我想对所有行对进行计算.有没有比使用嵌套for循环更简单的方法?
为了使这个具体,考虑一个十行的数据框,我想计算所有(45)个可能的对之间的分数差异.
> 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
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用嵌套for循环进行此计算,但是有更好的(更多R-ish)方法吗?
这里另一种解决方案使用combn:
df <- data.frame(ID=1:10,Score=4*10:1)
cm <- combn(df$ID,2)
delta <- df$Score[cm[1,]]-df$Score[cm[2,]]
Run Code Online (Sandbox Code Playgroud)
或更直接
df <- data.frame(ID=1:10,Score=4*10:1)
delta <- combn(df$ID,2,function(x) df$Score[x[1]]-df$Score[x[2]])
Run Code Online (Sandbox Code Playgroud)