Load Data From Your R Script Directly, No Files Needed

Ran across this nice little trick a few months back. One of the things I miss about SAS was the ability to copy/paste data directly into a SAS script. While it’s nice to load from an external file, for small datasets it can be more useful to have everything in just one file. This is especially useful with students who have trouble understanding the concept of a working directory or file paths in a smartphone app dominated world.

Here’s what I found months ago (I believe on Stack Overflow):

Input = ("Student Pretest Posttest
A 25 27
B 23 23
C 21 22
D 23 29
E 23 24
F 21 19
"); 
Data = read.table(textConnection(Input),header=TRUE)
t.test(Data$Pretest,Data$Posttest,paired=T)

There are no line numbers on that snippet – you’ve simply got 5 variables with 5 lines of data. The data is then read through a textConnection function into a data table. You can now work with it as you would any other data set.

Leave a Reply