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?
CodePudding user response:
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.
CodePudding user response:
What about this?
items <- 'c("a", "b", "c", "d")'
items.txt <- sprintf('"y <- %s"', items)
cat(items.txt)
# "y <- c("a", "b", "c", "d")"
CodePudding user response:
Another option is glue
glue::glue("y <- {items}")
y <- c("a", "b", "c", "d")
data
items <- 'c("a", "b", "c", "d")'