Loading and storing data with the keyboard and clipboard
Problem
You want to enter data using input from the keyboard (not a file).
Solution
Data input
Suppose this is your data:
size weight cost
small 5 6
medium 8 10
large 11 9
Loading data from keyboard input or clipboard
One way enter from the keyboard is to read from standard input (stdin()
).
# Cutting and pasting using read.table and stdin()
data <- read.table(stdin(), header=TRUE)
# You will be prompted for input; copy and paste text here
# Or:
# data <- read.csv(stdin())
You can also load directly from the clipboard:
# First copy the data to the clipboard
data <- read.table('clipboard', header=TRUE)
# Or:
# data <- read.csv('clipboard')
Loading data in a script
The previous method can’t be used to load data in a script file because the input must be typed (or pasted) after running the command.
# Using read.table()
data <- read.table(header=TRUE, text='
size weight cost
small 5 6
medium 8 10
large 11 9
')
For different data formats (e.g., comma-delimited, no headers, etc.), options to read.table()
can be set. See ../Loading data from a file for more information.
Data output
By default, R prints row names. If you want to print the table in a format that can be copied and pasted, it may be useful to suppress them.
print(data, row.names=FALSE)
#> size weight cost
#> small 5 6
#> medium 8 10
#> large 11 9
Writing data for copying and pasting, or to the clipboard
It is possible to write delimited data to terminal (stdout()
), so that it can be copied and pasted elsewhere. Or it can be written directly to the clipboard.
write.csv(data, stdout(), row.names=FALSE)
# "size","weight","cost"
# "small",5,6
# "medium",8,10
# "large",11,9
# Write to the clipboard (does not work on Mac or Unix)
write.csv(data, 'clipboard', row.names=FALSE)
Output for loading in R
If the data has already been loaded into R, the data structure can be saved using dput()
. The output from dput()
is a command which will recreate the data structure. The advantage of this method is that it will keep any modifications to data types; for example, if one column consists of numbers and you have converted it to a factor, this method will preserve that type, whereas simply loading the text table (as shown above) will treat it as numeric.
# Suppose you have already loaded data
dput(data)
#> structure(list(size = structure(c(3L, 2L, 1L), .Label = c("large",
#> "medium", "small"), class = "factor"), weight = c(5L, 8L, 11L
#> ), cost = c(6L, 10L, 9L)), .Names = c("size", "weight", "cost"
#> ), class = "data.frame", row.names = c(NA, -3L))
# Later, we can use the output from dput to recreate the data structure
newdata <- structure(list(size = structure(c(3L, 2L, 1L), .Label = c("large",
"medium", "small"), class = "factor"), weight = c(5L, 8L, 11L
), cost = c(6L, 10L, 9L)), .Names = c("size", "weight", "cost"
), class = "data.frame", row.names = c(NA, -3L))