Iain S
Iain S

Reputation: 2713

Paste large amount of data to clipboard in R

How do you paste a large amount of data onto the clipboard in R?

You can use write.table to paste to the clipboard, or to the (slightly) larger 128kb clipboard that Windows introduced since NT:

write.table(mtcars, "clipboard-128", sep="\t", row.names=FALSE)

But if you try to paste a large data frame, you receive an error:

big = data.frame(a=sample(LETTERS, 100000, replace=TRUE), b=rnorm(100000), c=rnorm(100000))
write.table(big, "clipboard-128", sep="\t", row.names=FALSE)

Warning message:
In .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol,  :
  clipboard buffer is full and output lost

What ways are there to get a large amount of data onto the clipboard in a format that is readable by other programs such as Excel?

Upvotes: 6

Views: 6752

Answers (2)

Sowmya S. Manian
Sowmya S. Manian

Reputation: 3833

Change 128 to 16384, warning would go away. You need to increase the limit. After executing the below command, you can easily paste in Excel directly.

    write.table(big, "clipboard-16384", sep="\t", row.names=FALSE)

Upvotes: 12

Iain S
Iain S

Reputation: 2713

If you want to paste more than 128kb of data, then you'll have to do it as a string. You can paste very large tables in markdown format using writeClipboard(knitr::kable(big)), but this involves using a large package and gives a table with a lot of formatting characters.

This code below uses toString() to convert the data.frame into a string, then changes the format to be tab delimited with newline characters between rows. This lets you copy large data tables (tested up to 10 MB without problem).

# copy a big data.frame to clipboard
writeBigClipboard = function(x)
{
    # convert x to a data.frame of char 
    for(col in 1:ncol(x))
        x[ , col] = as.character(x[ , col])

    # now convert its transpose into a string - so we get c(1st row), c(2nd row), ...
    x = as.data.frame( t(x), stringsAsFactors=FALSE)
    x = toString(x)

    # convert the delimiter from comma to tab
    x = gsub('\", \"', '\t', x, fixed=TRUE)

    # convert EOL to a newline character
    x = gsub('\"), c(\"', '\n', x, fixed=TRUE)

    # chop off the first c(\" and the last \")
    x = substr(x, 4, nchar(x)-2)

    # now paste the goodies into excel
    writeClipboard(x)
}

Example:

big = data.frame(a=sample(LETTERS, 100000, replace=TRUE), b=rnorm(100000), c=rnorm(100000))
writeBigClipboard(big)

This is quite resource intensive though, perhaps a more efficient solution exists?

Upvotes: -1

Related Questions