0

I would like to write several R source codes in a loop. However I am not getting a functional source file. That´s what I tried:

for(k in 1:10){
    cod <- 'x <- 1+k
         nam <- paste0(x, ".txt")
         write.table(x, nam)'
    cod <- gsub("x", k, cod)
    file <- paste0("source", k, ".R")
    dput(cod, file=file)}

Strictly speaking, I would like to get exactly the code in the cod object in 10 sources codes (differing by the k, which go from 1 to 10). Actually this code produce all the 10 files, but they contain strange characters and are no functional at all.

5
  • Replace dput with writeLines(cod, file) Commented Jan 19, 2016 at 18:11
  • dput writes an ASCII text representation of an R object, it's not mean for saving output. Use writeLines, sink, cat Commented Jan 19, 2016 at 18:12
  • Are you sure you actually want to do this? It seems very strange. What are you doing with these R files once you've made them? Also, your first line ends up as things like 5 <- 1+k because you substitute x with the value of k. What is going on? Commented Jan 19, 2016 at 18:14
  • @Spacedman, probably there is a much faster way to do what I want. Nevertheless, using several source codes is possible to run much faster than a canonical loop. Commented Jan 19, 2016 at 19:02
  • 1
    Why is it faster? Because you can run them in parallel? Sure, but don't duplicate the code. Put the code in one file as a function can call that from 10 scripts that just have source("code.R"); dothing(1) and dothing(2) and so on. Or better still parameterise the script and use littler. Commented Jan 19, 2016 at 19:06

1 Answer 1

1

Try to modify to writeLines from put, also change your formatting of string as follow:

for(k in 1:10) {
  cod <- 'x <- 1+k\nnam <- paste0(x, ".txt")\nwrite.table(x, nam)'
  cod <- gsub("x", k, cod)
  file <- paste0("source", k, ".R");
  writeLines(cod, file)
}
Sign up to request clarification or add additional context in comments.

3 Comments

It worked well! However, in my real code I have some characters which seems to be missed in the final source.R files. For example, I used write.table(x, nam, sep="\t"), which is modified wrongly to write.table(x, nam, sep=" "). Do you have any idea to deal with that?
Sometimes, \t will look like a space given the width of other data columns, but yet may be a tab. Also, make sure to use row.names = FALSE, quote = FALSE options to write.table.
I also got a problem in another section with the ` character: list.files(pattern = "\\.txt$")` was been turned into list.files(pattern = "\.txt$") given the follow error when I tried to execute the source: Error: '\.' is an unrecognized escape in character string starting ""\." Execution halted

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.