How do I save the results of a for-loop as a character string?

I’ve managed to automate some tedious code-writing with something like the following:

codes<-c("code1", "code2","code3")
for(i in codes){print(paste0("repetitivetext",i))}

yielding something like the following output:


Now I want to add the beginning and end of the code. I write:

paste0("beginning",for(i in codes){print(paste0("repetitivetext",i))},"end")¨

Hoping to get something like:


Instead I get:


How do I get my desired output? Is there for instance a way of collapsing the output of the for loop into a single character string (I already tried the collapse-option in paste0)?

This code segment will then have to be pasted together with other similarly created segments, so the lines must be saved in the correct order and they need to be saved as a single character string.

>Solution :

First, define an empty vector output to hold the result of the for loop (iff you want to use one, as there are more economical solutions readily available as noted by others):

output <- c()
for(i in codes){
  output[i] <- paste0("repetitivetext",i)

Then simply paste0 the text elements around output:

paste0("beginning", output, ,"end")
[1] "beginningrepetitivetextcode1end" "beginningrepetitivetextcode2end" "beginningrepetitivetextcode3end"

If you want to have it all in one chunk, add the collapse argument:

paste0("beginning",output,"end", collapse = "")
[1] "beginningrepetitivetextcode1endbeginningrepetitivetextcode2endbeginningrepetitivetextcode3end"


codes<-c("code1", "code2","code3")

Leave a Reply