2011-12-19 48 views
1

我有一组数据,如:R - 列子集之间的相关性 - 参考当前行

 name  Exp1Res1 Exp1Res2 Exp1Res3 ExpRes1 Exp2Res2 Exp3Res3 

[1]  ID1   5   7   9   7   9  2 

[2]  ID2   6   4   2   9   5  1 

[3]  ID3   4   9   9   9   11  2 

我需要确定每个行的实验1和2之间的相关性。由于在我的数据集(FullSet)中实际上有37列和100,000行,我原来的循环解决方案太慢(参见下文),所以我想优化。

我原来的解决方案是;

df <- data.frame(matrix(ncol = 5, nrow = dim(FullSet)[1])) 
names(df)<-c("ID","pearson","spearman") 
for (i in seq(1, dim(FullSet)[1])) 
{ 
    pears=cor(as.numeric(t(FullSet[i,2:19])),as.numeric(t(FullSet[i,20:37])), method="pearson") 
    spear=cor(as.numeric(t(FullSet[i,2:19])),as.numeric(t(FullSet[i,20:37])), method="pearson") 
    df[i,]<-c(FullSet[i,1],pears,spear) 
} 

我觉得应该这样工作;

FullSet$pearson<-cor(as.numeric(t(FullSet[,2:19])),as.numeric(t(FullSet[,20:37])), method="pearson") 

,但我不知道是否/如何在转引用只要当前行 -

t(FullSet[,2:19]) - which should read something like t(FullSet[<currow>,2:19]). 

帮助,将不胜感激 - 我不知道我的做法是正确的,甚至。

输出应该像(结果是不正确的 - 例如只)

 name  Pearson  Spearman 

[1]  ID1   0.8   .75 

[2]  ID2   0.9   .8 

[3]  ID3   0.85   .7 

回答

4

怎么样将它带到格式:

ID EXP Res 
1 1 . 
1 1 . 
1 2 . 
1 2 . 

使用reshape,然后让plyr做的工作:

require(plyr) 
ddply(df, .(ID, EXP), summarize, cor(...)) 

会这样吗?如果你单独为spearman和perason做。

+0

我已经将此标记为答案,因为它确实有效并且是一种替代方法(只是熔化和ddply),但它不会比循环方法更快。 – statler 2011-12-19 23:05:59