Search code examples
rreprex

How to transform a dataframe console output to its structure automatically


Unexperienced users of StackOverflow tend to provide console output of the data they use:

  id name
1  1 john
2  2 mary

Users with more experience should encourage them to provide a Reproducible Example, or to use dput to provide data structure, but they don't always have time.
Do you know of a package/function allowing to copy the console output of a dataframe and to generate out of the clipboard the associated structure?

structure(list(id = c(1, 2), name = c("john", "mary")), class = "data.frame", row.names = c(NA, 
-2L))

To make it short, I'm looking for and inverted dput.
The reprex package allows this kind of manipulation, for example clean-up console output, but I didn't find in it the function I'm looking for!


Solution

  • Using read.table.

    x <- "
      id name
    1  1 john
    2  2 mary
    "
    
    fun <- function(x, header=TRUE) dput(read.table(header=header, text=x))
    fun(x)
    # structure(list(id = 1:2, name = c("john", "mary")), class = "data.frame", row.names = c("1",
    # "2"))