0

For context, I am running DESEQ2 and want to write CSV result files for different comparisons.

I am trying to create a for loop such that I can create CSV files for the different result files.

My results objects are obtained by the DESEQ2 function: results()

A <- results(dds,contrast=c("condition","treatment1","untreated")
B <- results(dds,contrast=c("condition","treatment2","untreated")
C <- results(dds,contrast=c("condition","treatment3","untreated")
D <- results(dds,contrast=c("condition","treatment4","untreated")

I would like to get: A.csv, B.csv, C.csv, etc.

My code is as follows:

results <- c(A,B,C,D)

for (x in results) {
write.csv(x, file = paste(x,".csv"))
}

However, when I run my chunk, it says:

Error in for (x in results) { : invalid for() loop sequence
2
  • 1
    Try for (x in seq_along(results)) {... Commented Nov 8, 2022 at 1:01
  • Hi Conor, thanks for your help :) Unforuntately, I still get the same error. Commented Nov 9, 2022 at 20:19

1 Answer 1

1

This method uses a list of string names of the objects to be written. Loop over the list of strings. Use get() to get the object from the individual string names. And use paste0() to ensure there was not a space in the file name:

results <- c("A","B","C","D")

for (x in results) {
  write.csv(get(x), file = paste0(x,".csv"))
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi M.Viking, when I try your code, I'm getting a message: "Error in get(x) : invalid first argument"
That message means there is not object with that name. Let's troubleshoot. First, comment out the #write.csv(... line, and insert print(x). do the string names print properly? Next, test the string names for example, does head(get("A")) work? The output should be identical to head(A).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.