I decided to add this solution too because I found that dput()
wasn't working for what I was trying to do. I have a shiny
app that uses knitr
to make reports based on the user session, and I use knit_expand()
before rendering my .Rmd to port user parameters from the shiny session into the .Rmd.
Without going into too much detail, I have the need to port vectors "as is", because they will be written into lines of code in the .Rmd that someone will run. For this case, dput()
didn't work because the output is only spit to the console, and the dump()
method works but I didn't want to write new files every time and delete them.
There might be a better way, but I wrote a function that returns a character object of the vector "as is". It handles both numeric and character vectors (it throws quotes around each member of the character vector). It also handles single inputs and simply returns them as they are. It's not pretty, and I'm sure there are more efficient ways to write it, but it works perfectly for my needs. Thought I'd add this solution to the fray.
printVecAsis <- function(x) {
ifelse(length(x) == 1, x,
ifelse(is.character(x), paste0("c(", paste(sapply(x, function(a) paste0("\'",a,"\'")), collapse=", "), ")"),
paste0("c(", paste(x, collapse=", "), ")")))}
deparse(x)
.