iwannabetheverybest21
iwannabetheverybest21

Reputation: 19

Creating a for loop that writes a CSV file for each iteration

I am trying to iterate through a vector that runs a function for each iteration and writes an output of that function to a .csv file.

Each entry in gene_ID_temp is a character that is inputted into transcript_proportions. For each entry, I am trying to run transcript_proportions and write the output to a .csv file with a different number.

gene_ID=data.frame(RNA_transcript_RPKM[,773])
  gene_ID_unique <- unique(gene_ID)
  gene_ID_temp=data.frame(gene_ID_unique[1:3,])
  a=1
  for (i in gene_ID_temp)
{
  transcript_proportions(RNA_transcript_RPKM_MUSCLE,i)
  write.csv(Regression_Values,paste0(a,".csv"))

  a=a+1
} 

Currently, it seems to be only writing one file "1.csv" that is a combination of the outputs from the iterations and it isn't writing a separate file for each iteration. Also I'm not sure that the "a" variable is actually changing.

How do I solve the problem?

Upvotes: 1

Views: 406

Answers (2)

Phil Hunter
Phil Hunter

Reputation: 1

This could be down to two issues with your gene_ID_temp object

  1. As it is a data frame, you would need to specify the length of i, preferably with nrow(), but try length() as well!
  2. Any strings will get converted into factors instead of characters, which could cause issues.

I would check out the purrr package for dealing with this sort of task, or if you need to stick with base R, get familiar with the apply functions :-)

Upvotes: 0

Jeffrey Brabec
Jeffrey Brabec

Reputation: 521

I think one issue you might be having is that you haven't specified the range of numbers for your for loop to loop through. Trying something like

for i in 1:length(gene_ID_temp)

That without seeing the output of your code or running it myself I can't be sure if that will fix your problem but that might get you some of the way there!

Upvotes: 3

Related Questions