R: adding content to data frame and export

Continuely add content (row or column) to a data frame and then export it to file.

Just as a self-reminder on how to add content from a loop.

Also useful functions to combine data frame: cbind and rbind.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
## create an empty data frame
expotable<-data.frame()

## add lines from variable values
for (i in 1:no.tests) {
  fisherp<-fisher.test(matrix(c(fishertable[i,'V3'],fishertable[i,'V4'],fishertable[i,'V5'],fishertable[i,'V6']),nrow=2))$p.value  # alternative ="greater"
  fisherpadj<-fisherp*no.tests
  newline<-cbind(fishertable[i,], formatC(fisherp, format = "f",digits = 4), formatC(fisherpadj, format = "f", digits = 4))
  expotable<-rbind(expotable, newline)
}

## modify the column names
colnames(expotable)<-c("Block","Pfam", "anno_local", "anno_all", "nonanno_local", "nonanno_all", "FisherP", "FisherPadj")

## now can export the data frame
write.table(expotable, file="testResults.txt", row.names = F, sep="\t", quote = F)
comments powered by Disqus
CC-BY-NC 4.0
Built with Hugo Theme Stack