Search code examples
rtidyverse

Is is possible to convert a dataframe object to a tribble constructor?


I have data that looks like this:

library(tidyverse)
df <- tibble(
    x = c(0, 179, 342, 467, 705, 878, 1080, 1209, 1458, 1639, 1805, 2000, 2121, 2339, 2462, 2676, 
      2857, 3049, 3227, 3403, 3583, 3651, 4009, 4034, 4151, 4194, 4512, 4523, 4679, 5789), 
    y = c(4.7005, 4.8598, 5.0876, 5.0938, 5.3891, 5.6095, 5.8777, 6.0064, 6.3063, 6.4723, 6.6053, 
          6.8145, 6.9078, 7.1701, 7.2633, 7.3865, 7.5766, 7.644, 7.8018, 7.9505, 8.0974, 8.1937, 
          8.2391, 8.294, 8.3143, 8.3452, 8.5092, 8.5172, 8.5993, 9.0275))

Is it possible to convert my dataframe/tibble object to a tribble "constructor"?

I'm looking for something like dput, but more lightweight and specifically for dataframes.


Solution

  • I think mc_tribble is a better name, and it looks like you can just condense it to:

    mc_tribble <- function(indf, indents = 4, mdformat = TRUE) {
      name <- as.character(substitute(indf))
      name <- name[length(name)]
    
      meat <- capture.output(write.csv(indf, quote = TRUE, row.names = FALSE))
      meat <- paste0(
        paste(rep(" ", indents), collapse = ""),
        c(paste(sprintf("~%s", names(indf)), collapse = ", "),
          meat[-1]))
    
      if (mdformat) meat <- paste0("    ", meat)
      obj <- paste(name, " <- tribble(\n", paste(meat, collapse = ",\n"), ")", sep = "")
      if (mdformat) cat(paste0("    ", obj)) else cat(obj)
    }
    

    Try it out:

    short_iris <- head(iris)
    
    mc_tribble(short_iris)
    

    Improvements:

    • Shorter code
    • Captures the name of the "tibble"
    • Has an argument for indenting
    • Has an argument for conveniently adding 4 spaces for pasting on Stack Overflow
    • Sounds more tasty

    I've added this to my "SOfun" package. You can install it with:

    source("http://news.mrdwab.com/install_github.R")
    install_github("mrdwab/overflow-mrdwab") # for writeClip -- plus it's awesome
    install_github("mrdwab/SOfun")
    

    Usage is then simply:

    library(SOfun)
    mc_tribble(short_iris)
    

    Advantages:

    • Now copies the output to your clipboard (if you have "overflow" installed)
    • Even more affordable than before!