Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use the Clipboard to Copy and Paste Data in R

Another way of importing data interactively into R is to use the Clipboard to copy and paste data. To import data from the Clipboard, use the readClipboard() function. For example, select cells B2:B4 in the periodic table spreadsheet, press Ctrl+C to copy those cells to the Clipboard, and then use the following R code:

> x <- readClipboard()
> x
[1] "Hydrogen" "Helium"  "Lithium"

As you can see, this approach works very well for vector data (in other words, a single column or row of data). But things get just a little bit more complicated when you want to import tabular data to R.

To copy and paste tabular data from a spreadsheet, first select a range in your sheets (for example, cells B1:D5). Then use the readClipboard() function and see what happens:

> x <- readClipboard()
> x
[1] "Name\tSymbol\tGroup" "Hydrogen\tH\t1"   "Helium\tHe\t1"
[4] "Lithium\tLi\t1"   "Beryllium\tBe\t2"

This rather unintelligible result looks like complete gibberish. If you look a little bit closer, though, you’ll notice that R has inserted lots of "\t" elements into the results. The "\t" is the R way of indicating a tab character — in other words, a tab separator between elements of data.

The backslash in "\t" is called an escape sequence.

The very powerful read.table() function imports tabular data into R. You can customize the behavior of read.table() by changing its many arguments. Pay special attention to the following arguments:

  • file: The name of the file to import. To use the Clipboard, specify file = "clipboard".

  • sep: The separator between data elements. In the case of Microsoft Excel spreadsheet data copied from the Clipboard, the separator is a tab, indicated by "\t".

  • header: This argument indicates whether the Clipboard data includes a header in the first row (that is, column names). Whether you specify TRUE or FALSE depends on the range of data that you copied.

  • stringsAsFactors: If TRUE, this argument converts strings to factors. It’s FALSE by default.

    > x <- read.table(file = "clipboard", sep = "\t", header=TRUE)
    > x
        Name Symbol Group
    1 Hydrogen   H   1
    2  Helium   He   1
    3  Lithium   Li   1
    4 Beryllium   Be   2

Although R offers some interactive facilities to work with data and the Clipboard, it’s almost certainly less than ideal for large amounts of data. If you want to import large data files from spreadsheets, you’ll be better off using CSV files.

Note: Unfortunately, readClipboard() is available only on Windows.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!