1

in an application I use RODBC to access a database. Specifically I call a function like this: sqlQuery(conn, qry), where qry is a string, and conn is a RODBC connection object.

Is it possible to paste this into a file in such a way that if I copy and paste the file contents into the terminal, I will reproduce the exact function call?

For example, if I make a dataframe: df <- data.frame(test = c(1, 2, 3)), I can call dput(df), which will return: structure(list(frank = c(1, 2, 3)), class = "data.frame", row.names = c(NA, -3L))

If I copy and paste that into the terminal, I will get the original dataframe.

It would be really convienient for debugging if I could do something like this for sqlQuery(conn, qry)

Frank
  • 952
  • 1
  • 9
  • 23
  • What is your expected output? – dave-edison May 08 '20 at 17:30
  • something that I can copy and paste into r studio terminal and produce the same error without loading everything up manually (database connection, query string, ect...) – Frank May 08 '20 at 19:38
  • If you're using RStudio, maybe look into making a custom [snippet](https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets)? – dave-edison May 08 '20 at 22:22

1 Answers1

0

Assuming that dput works Ok for your objects, and that we can assume that any required libraries are loaded and/or functions defined, why not just build the function call string like this:

Define 'fput' function to generate pastable string that will replicate a function call:

fput = function( fun_string, ... ) {
    args=as.list(match.call(expand.dots=F))[["..."]]
    arg_strings=lapply(args,function(arg) capture.output(do.call(dput,list(arg),envir=parent.frame())))
    arg_string=paste(arg_strings,collapse=",")
    paste(fun_string,"(",arg_string,")")
}

Example:

Sample data:

a=1:10
b=a^2

Sample function call to replicate as pastable string:

plot(a,b)

Call fput():

fput( "plot", a, b )

Output:

[1] "plot ( 1:10,c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100) )"

Check: copy-paste of output generates same result as plot(a,b)