R因子在循环中构建完整的数据帧

时间:2017-02-10 17:47:57

标签: r loops

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

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

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

但是Label列中包含了进入“fxn”的所有因素。

错误:

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

1 个答案:

答案 0 :(得分: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)
}

事先初始化data.frame,您不需要if语句。另外data是R中的函数,因此我将变量数据重命名为datav。