0

I want to print out the content of a dataframe adj_expression variable. This loops through 1:449 which is the number of genes.

for (i in 1:n_genes) {
        cat(i, "/", n_genes, "\n")
        gene <- genes[i]
        gene_name <- gene_annot$gene_name[gene_annot$gene_id == gene]
        gene_type <- get_gene_type(gene_annot, gene)
        coords <- get_gene_coords(gene_annot, gene)
        cis_gt <- get_cis_genotype(gt_df, snp_annot, coords, cis_window)
        if (all(is.na(cis_gt))) {
          # No snps within window for gene.
          model_summary <- c(gene, gene_name, gene_type, alpha, 0, 0, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
          write(model_summary, file = model_summary_file, append = TRUE, ncol = 24, sep = '\t')
          next
        }
        model_summary <- c(gene, gene_name, gene_type, alpha, ncol(cis_gt), 0, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
        if (ncol(cis_gt) >= 2) {
          expression_vec <- expr_df[,i]
          adj_expression <- adjust_for_covariates(expression_vec, covariates_df)
          adj_expression <- as.matrix(adj_expression[(rownames(adj_expression) %in% rownames(cis_gt)),])
}

I used

write.table(adj_expression,file="s_expr.txt",header=T,sep="\t")

But it only print the last content of i rather than the entire 1:449 length.

Phil
  • 7,287
  • 3
  • 36
  • 66
  • I don't see a data frame here. But if you do have one, print(dfname$colname) will do it. As in df <- data.frame(a=c(1,2,3),b = c(3,4,5)) print(df$a) R takes care of all the looping for you if you'll let it. – John Garland Aug 12 '22 at 21:21
  • You could turn the for loop as a function, that return the adj_expression for one of the n_genes. Then you loop the function separately with with something like [this](https://stackoverflow.com/questions/26707724/writing-multiple-data-frames-into-csv-files-using-r) to output them into individual output. – Adam Quek Aug 13 '22 at 02:17

0 Answers0