Maybe I\'m imagining this, but I think there is a built-in R function that lets you print an R vector (and possibly other objects like matrices and data frames) in the forma
dput
maybe?
> test <- c(1,2,3)
> dput(test)
c(1, 2, 3)
You can also dump
out multiple objects in one go to a file that is written in your working directory:
> test2 <- matrix(1:10,nrow=2)
> test2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> dump(c("test","test2"))
dumpdata.r
will then contain:
test <-
c(1, 2, 3)
test2 <-
structure(1:10, .Dim = c(2L, 5L))
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=", "), ")")))}