Reputation: 5
I want to replace %s as a vector.
So, I coded as below:
items <- c("a", "b", "c", "d")
items.txt <- sprintf("y <- c(%s)", items)
My expected result is:
"y <- c("a", "b", "c", "d")"
But real result is:
"y <- c(a)" "y <- c(b)" "y <- c(c)" "y <- c(d)"
Thus I tried as follows:
items.txt <- sprintf("y <- c(%s)", paste(items, collapse - ","))
items.txt <- sprintf("y <- c(%s)", paste(items, collapse - '","'))
But these are not working.
Are there are any ideas for solving this problem?
Upvotes: 0
Views: 352
Reputation: 51974
What about this?
items <- 'c("a", "b", "c", "d")'
items.txt <- sprintf('"y <- %s"', items)
cat(items.txt)
# "y <- c("a", "b", "c", "d")"
Upvotes: 1
Reputation: 226172
This seems easiest to me:
s <- sprintf("y <- c(%s)", paste(sprintf('"%s"',items), collapse=","))
Note that print(s)
will look weird because of the backslashes protecting the quotation marks. cat(s,"\n")
looks more normal:
y <- c("a","b","c","d")
dput(items, textConnection("s", "w"))
might also be useful.
Upvotes: 1