Skip to content
Prev 305719 / 398506 Next

Parsing "back" to API strcuture

Problem solved by Josh O'Brien on stackoverflow,
http://stackoverflow.com/questions/12393004/parsing-back-to-messy-api-strcuture/12435389#12435389

some_magic <- function(df) {
    ## Replace NA with "", converting column types as needed
    df[] <- lapply(df, function(X) {
                if(any(is.na(X))) {X[is.na(X)] <- ""; X} else {X}
            })

    ## Print integers in first column as 2-digit character strings
    ## (DO NOTE: Hardwiring the number of printed digits here is probably
    ## inadvisable, though needed to _exactly_ reconstitute RAW.API.)
    df[[1]] <- sprintf("%02.0f", df[[1]])

    ## Separately build header and table body, then suture them together
    l1 <- paste(names(df), collapse=",")
    l2 <- capture.output(write.table(df, sep=",", col.names=FALSE,
                                     row.names=FALSE))
    out <- paste0(c(l1, l2, ""), collapse="\n")

    ## Reattach attributes
    att <- list("`Content-Type`" = structure(c("text/html", "utf-8"),
                .Names = c("", "charset")))
    attributes(out) <- att
    out
}

identical(some_magic(df), RAW.API)
# [1] TRUE
On Thu, Sep 13, 2012 at 11:32 AM, Eric Fail <eric.fail at gmx.us> wrote: