Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an accumulated array of strings from a string array

I have this:

str <- c("var1", "var2", "var3")

And I want to generate the following array of strings:

"c ~ var1"
"c ~ var1 + var2"
"c ~ var1 + var2 + var3"

I know I can hardcode this, since there are only 3 strings, but I want a method for a vector of any size. Is there a simple way to achieve this?

like image 958
dpalma Avatar asked Jun 23 '26 19:06

dpalma


1 Answers

You could try this:

out <- vector()
out[1] <- paste("c ~",str[1])
for (i in 2:length(str)) out[i] <- paste(out[i-1], "+", str[i])
like image 196
RHertel Avatar answered Jun 25 '26 11:06

RHertel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!