Read Your Dataset in R From Copy Paste Text

Liang / 2018-05-04


Problem

Sometimes, we may want import a small dataset to our R code. And this may be annoying if we still need store data into a csv or txt file and then read dataset in from a file. A convenient way is read data in just from copy paste text. This post will solve this problem.

Solution

Fisrt we need to store the data in a character variable

data.text <- "X   X400    X80     X8 CONTROL
1      CA  87743 157938 184261  114066
2      CA  78969 166712 166712   61420
3      CA  52646     NA 122841   87743
4      CA  61420 114066 149164      NA
5      CA  70195     NA 140389   61420
6      CA     NA 140389     NA   78969
7  Etanol  78969 228133 166712  114066
8  Etanol 122841 245682 122841   61420
9  Etanol     NA     NA 228133   87743
10 Etanol  61420 166712 105292      NA
11 Etanol     NA 175487 157938   61420
12 Etanol  78969 201810     NA   78969
13     SA 122841 105292     NA  114066
14     SA 140389  78969 254456   61420
15     SA  96518  61420 122841   87743
16     SA  87743  52646     NA      NA
17     SA 105292 122841 184261   61420
18     SA     NA  78969 210584   78969"

Next, we can use textConnection to create a virtual file and then use read.table to read the string into a data frame

read.table(textConnection(data.text), header=TRUE)
##         X   X400    X80     X8 CONTROL
## 1      CA  87743 157938 184261  114066
## 2      CA  78969 166712 166712   61420
## 3      CA  52646     NA 122841   87743
## 4      CA  61420 114066 149164      NA
## 5      CA  70195     NA 140389   61420
## 6      CA     NA 140389     NA   78969
## 7  Etanol  78969 228133 166712  114066
## 8  Etanol 122841 245682 122841   61420
## 9  Etanol     NA     NA 228133   87743
## 10 Etanol  61420 166712 105292      NA
## 11 Etanol     NA 175487 157938   61420
## 12 Etanol  78969 201810     NA   78969
## 13     SA 122841 105292     NA  114066
## 14     SA 140389  78969 254456   61420
## 15     SA  96518  61420 122841   87743
## 16     SA  87743  52646     NA      NA
## 17     SA 105292 122841 184261   61420
## 18     SA     NA  78969 210584   78969

Problem solved!

Update

A more convenient way is use read.table directly.

dw <- read.table(header=T, text='
 sbj f1.avg f1.sd f2.avg f2.sd  blabla
   A   10    6     50     10      bA
   B   12    5     70     11      bB
   C   20    7     20     8       bC
   D   22    8     22     9       bD
 ')
dw
##   sbj f1.avg f1.sd f2.avg f2.sd blabla
## 1   A     10     6     50    10     bA
## 2   B     12     5     70    11     bB
## 3   C     20     7     20     8     bC
## 4   D     22     8     22     9     bD

Reference: Copy and paste small data sets into R

Last modified on 2018-05-04