# Copy and paste small data sets into R

How can I embed a small data set into my R code? That was the question I came across today, when I prepared my talk about Dynamical Systems in R with simecol for the forthcoming Cologne R user group meeting.

I wanted to add all the R code of the talk to the last slide. That's easy, but the presentation makes use of a small data set of 3 columns and 21 rows. Surely there must be an elegant solution that I can embed the data into the R code, without writing x <- c(x1, x2,...).

Of course there is a solution, but let's look at the data first. It shows the numbers of trapped lynx and snowshoe hares recorded by the Hudson Bay company in North Canada from 1900 to 1920.

![](/img/magesblog/Smalldata.png) Data sourced from Joseph M. Mahaffy. Original data believed to be published

in E. P. Odum (1953), Fundamentals of Ecology, Philadelphia, W. B. Saunders.
Another source with data from 1845 to 1935 can be found on D. Hundley's page.

My first idea was to store the data in a character variable:

HaresLynxObservations <- "Year  Hares.x.1000  Lynx.x.10001900 30 41901 47.2 6.11902 70.2 9.81903 77.4 35.21904 36.3 59.41905 20.6 41.71906 18.1 191907 21.4 131908 22 8.31909 25.4 9.11910 27.1 7.41911 40.3 81912 57 12.31913 76.6 19.51914 52.3 45.71915 19.5 51.11916 11.2 29.71917 7.6 15.81918 14.6 9.71919 16.2 10.11920 24.7 8.6"

Now, how do I transform the string into a data frame? My initial thought was to write the string into a temporary file and to read it into R again:

fn <- tempfile()cat(HaresLynxObservations, file=fn)read.table(fn, header=TRUE)

However, I was convinced that there was a better, more elegant way. And indeed there is, via connections. A good starting point to learn more about connections in R is Brian Ripley's article on that topic in R News and of course the R Data Import/Export manual:

Text connections are another source of input. They allow R character vectors to be read as if the lines were being read from a text file. A text connection is created and opened by a call to textConnection, which copies the current contents of the character vector to an internal buffer at the time of creation.

Wonderful, textConnection provides basically a virtual file and hence I can use read.table again to read the string into a data frame:

read.table(textConnection(HaresLynxObservations), header=TRUE)

That' all I need to copy and paste small data sets into R.

For moving data between R and Excel via the clipboard see John Cook's post.