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:
"repetitivetextcode1"
"repetitivetextcode2"
"repetitivetextcode3"
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:
beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end
Instead I get:
"repetitivetextcode1"
"repetitivetextcode2"
"repetitivetextcode3"
"beginningend"
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.
CodePudding user response:
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"
Data:
codes<-c("code1", "code2","code3")
CodePudding user response:
collapse
without the loop should do:
paste0('beginning',
paste0('repetitivetext', codes, collapse = ''),
'end'
)
output:
## [1] "beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end"
CodePudding user response:
Actaully for
loops in R in certain cases can be replaced by vectorized functions:
codes <- c("code1", "code2", "code3")
codes2 <- paste0("repetitivetext", codes)
print(codes2)
Here is the output:
[1] "repetitivetextcode1" "repetitivetextcode2" "repetitivetextcode3"
And the resulting string can be also acheived without any loops:
paste0("beginning",
paste0(codes2, collapse = ""),
"end"
)
And you get the following output:
[1] "beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end"