2017-02-10 86 views
0

我正在尝试编写一个循环,对每个“标签”的3个样本的数据执行anova和TukeyHSD。这种情况下的标签是一种代谢途径。进入它的数据是在所述代谢途径中表达的基因。一个循环中的R因素来构建完整的数据帧

对于测试数据,我创建了一个小的df来重现我的错误。在我的实际数据中,我希望通过2个因素来执行此操作(不仅仅是一个),而且我还有成千上万的行。

library(reshape2) 
df<-melt(data.frame(sample1 = c(0,0,3,4,5,1),sample2 = c(1,0,0,4,5,0),sample3 = c(0,0,0,8,0,0),Label = c("TCA cycle", "TCA cycle","TCA cycle", "Glycolysis","Glycolysis","Glycolysis"),Gene = c("k1","k2","k3","k4","k5","k6"))) 

我的做法(注释我能的最佳方式!):

fxn<-unique(df$Label) #create list 
for (i in 1:length(fxn)){ 
if (!exists("data")){ #if the "data" dataframe does not exist, start here! 
    depth<-aov(df$value[df$Label==fxn[i]]~df$variable[df$Label==fxn[i]]) #perform anova on my "df", gene values as a factor of samples (for each "fxn") 
    hsd<-TukeyHSD(depth) #calculate tukeyHSD 
    data<-as.data.frame(hsd$`df$variable[df$Label == fxn[i]]`) #grab dataframe of tukey HSD output 
    data$Label<-fxn[i] #add in the Label name as a column (so it looks like my original df, but with TukeyHSD output for each pairwise comparison 
    data<-as.data.frame(data) 
} 
if (exists("data")){ #if "data" exists, do this: 
    tmpdepth<-aov(df$value[df$Label==fxn[i]]~df$variable[df$Label==fxn[i]]) 
    tmphsd<-TukeyHSD(tmpdepth) 
    tmpdata<-as.data.frame(tmphsd$`df$variable[df$Label == fxn[i]]`) 
    tmpdata$Label<-fxn[i] 
    tmpdata<-as.data.frame(tmpdata) 
    data<-rbind(data,tmpdata) #combine with original data 
    data<-as.data.frame 
    rm(tmpdata) 
    } 
} 

我想我的输出看起来像这样:

     diff  lwr  upr  p adj  Label 
sample2-sample1 -0.3333333 -8.600189 7.933522 0.9916089 Glycolysis 
sample3-sample1 -0.6666667 -8.933522 7.600189 0.9669963 Glycolysis 
sample3-sample2 -0.3333333 -8.600189 7.933522 0.9916089 Glycolysis 

但标签列有所有进入“fxn”的因素。

错误:

Error in rep(xi, length.out = nvar) : 
    attempt to replicate an object of type 'closure' 
+0

我也想知道如果我可以在这里使用rbind.fill而不是rbind。如果在某处丢失数据,这将有助于使该循环更加健壮,对吗? – shu251

+0

是的,没错! – HelloWorld

回答

1

你之前的RM(tmpdata伪)忘了在最后一行第二data。它应该是: data<-as.data.frame(data)

我我我实施改变了你的代码如下:

datav <- data.frame(diff = double(), 
    lwr = double(), 
    upr = double(), 
    'p adj' = double(), 
    'Label' = character()) 

for (fxn in unique(df$Label)){ 
    depth <- aov(df$value[df$Label==fxn] ~ df$variable[df$Label==fxn]) 
    hsd <- TukeyHSD(depth) 
    tmp <- as.data.frame(hsd$`df$variable[df$Label == fxn]`) 
    tmp$Label <- fxn 
    datav <- rbind(datav, tmp) 
} 

初始化前手你不需要if语句的data.frame。另外data是R中的一个函数,所以我将变量数据重命名为datav。

相关问题