Monday, September 14, 2020

Reading From and Writing To Clipboard (usage: copy a data table from a spreadsheet or paste a table into a spreadsheet)

wc <- wc.linux <- function(x) {
    ## Write to Clipboard
    ## Write a table/data frame "x" to the Clipboard for Excel use.
    ff <- pipe("xclip -i -selection clipboard", "w")
    utils::write.table(x, file=ff, sep="\t", col.names=T, row.names=F, na="")
    close(ff)
}


rc <- function(header, p=TRUE, ...){                       
    ## Read from Clipboard
    ## Check is Header Line exists.
    ## Checking if the first element in the first line is a numeric type or not.
    ## if "p=TRUE", print out the vector definition for copying 
    if (missing(header)) {
        if (is.numeric(unlist(read.delim("clipboard", nrows=1, header=F))[1]))
            header=F
        else
            header=T
    }

    a <- utils::read.delim("clipboard", header=header, as.is = TRUE, ...)
    if (p) {
        for (i in seq(ncol(a))) pvec(a[[i]], var=letters[(22+i) %% 26 + 1])
        return(invisible(a))
    } else {
        if (ncol(a) == 1 || nrow(a) == 1) {    # convert to a vector if there is only one column
            a <- unlist(a)
            cat("\nClipboard is read into a vector of length:", length(a), "\n")
        } else cat("Clipboard is read into a data.frame of dimension:", dim(a), "\n")
        print(head(a, n=3))
        return(invisible(a))
    }
}