How to Easily Read and Write Data from Clipboard in R



How to Easily Read and Write Data from Clipboard in R

This article describes how to read and write data from the clipboards using the R package clipr, which works well on Windows, OS X, and Unix-like systems.

Note that on Linux, you will need to install the system requirement, either xclip or xsel. This can be done using for example apt-get install xclip.



Contents:

Prerequisites

  1. Install from CRAN
install.packages("clipr")
  1. Load the package:
library("clipr")

Copy any data into R

my_data <- read_clip()
my_data

Copy data table from excel and import in R

The read_clip_tbl() function will try to parse clipboard contents from spreadsheets into data frames directly.

Step 1. Copy the data from excel

Copy data from excel to R

Step 2. Import the data from the clipboard into R

my_data <- read_clip_tbl()
my_data
## # A tibble: 11 x 6
##   name                mpg   cyl  disp    hp  drat
##   <chr>             <dbl> <int> <dbl> <int> <dbl>
## 1 Mazda RX4          21       6   160   110  3.9 
## 2 Mazda RX4 Wag      21       6   160   110  3.9 
## 3 Datsun 710         22.8     4   108    93  3.85
## 4 Hornet 4 Drive     21.4     6   258   110  3.08
## 5 Hornet Sportabout  18.7     8   360   175  3.15
## 6 Valiant            18.1     6   225   105  2.76
## # … with 5 more rows

Write data from R to clipboard

Write a data frame

  1. Write the data to the clipboard:
write_clip(mtcars)
  1. Paste the data into Excel: ctrl + c

Additional features

clipr returns the same object that was passed in.

res <- write_clip(c("Text", "for", "clipboard"))
res
## [1] "Text"      "for"       "clipboard"

To capture the string that clipr writes to the clipboard, specify return_new = TRUE. Character vectors with length > 1 will be collapsed with system-appropriate line breaks, unless otherwise specified

cb <- write_clip(c("Text", "for", "clipboard"), return_new = TRUE)
cb
## [1] "Text\nfor\nclipboard"
cb <- write_clip(c("Text", "for", "clipboard"), breaks = ", ", return_new = TRUE)
cb
## [1] "Text, for, clipboard"



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments