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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With