7.2 Clipboard Data
20200106 A useful trick to quickly ingest a small amount of
data into R is to read the data from the clipboard. That is, from a
selection that is made in some other application. For example, if a
CSV file is being viewed within a text editor, then some number of
rows and columns could be highlighted and copied (often by pressing
Ctrl-C) to the clipboard. The data can then be read into R using
the package readr (Wickham, Hester, and Bryan 2024). The function
readr::read_csv() can have as its first argument,
file=
readr::clipboard(), which
diverts input to come from the clipboard. Another use case is when a
small data sample is shared on a web page. The data can be highlighted
and copied to the clipboard to then be ingested into R.
Note the use below of col_names=
. Set to FALSE
it
indicates that the first row is not the column names, as might
typically be the case when selecting different ranges of rows from
sample data. Names like X1
and X2
will be
generated. If the first row does name the columns then simply remove
the option or else set it to TRUE
. It can also be a character
vector of names to be used for the columns.
library(readr) # Read/write delimited data: read_csv().
ds <- read_csv(clipboard(), col_names=FALSE)
ds
## # A tibble: 11 x 2
## X1 X2
## <chr> <dbl>
## 1 27 Jun 2020 -2149
## 2 09 Jun 2020 33.8
## 3 11 Jun 2020 56.3
## 4 11 Jun 2020 12.1
## 5 11 Jun 2020 10.6
## 6 11 Jun 2020 47.4
## 7 11 Jun 2020 41.7
## 8 12 Jun 2020 45.6
## 9 15 Jun 2020 1838.
## 10 15 Jun 2020 50.3
## 11 17 Jun 2020 58.8
Using base R a similar approach is available with the special string clipboard as the first argument in utils::read.table(), for example. This generally only works on Linux with X11.
References
Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0