3

How can I copy and paste data into R? For example, you see a small data set on the web, perhaps in a blog or here on StackOverflow, and you want that data set in your R session. This is a common task for many of us, and there are several ways to go about. Below I present a solution based on this blog post that I have found useful.

This question has of course been asked before, for example here and here however, these posts are rather old and overcrowded which makes finding a short working answer difficult.

Community
  • 1
  • 1
Samuel
  • 2,895
  • 4
  • 30
  • 45
  • So you think having even more questions asking the same thing will make it easier for future readers to find answers? My suggestion: instead of promoting the dup, delete your version and upvote the most helpful answers elsewhere. – GhostCat May 22 '17 at 03:02

1 Answers1

11

First, copy (e.g. "⌘ + C") the data set.

Then, paste (e.g. "⌘ + V") to create an R character vector:

x <- " A B C D 1: 2 2 5 3 2: 2 1 2 3 3: 3 4 4 3"

Next, use the read.table() function:

y <- read.table(text = x, header = TRUE)

Done! The data is now in a data frame:

class(y)
[1] "data.frame"

You might also want to check out the dput() function which writes an ASCII text representation of an R object that you can paste into your StackOverflow question or answer.

Samuel
  • 2,895
  • 4
  • 30
  • 45