R can read data stored in text (ASCII) files; three functions can be used: (1) read.table(), (2) scan() and (3) read.fwf(). The first two of these three functions are the most commonly used. Say we have a file mydata.dat in the D:\TEMP folder, we can type:
dat <- read.table("D:\\TEMP\\mydata.csv", header = TRUE, sep = ",")
The header = TRUE argument tells R to use the first line of data in the CSV file for the variable names. The sep = "," argument tells R that each column in the data set is separated by a comma. To avoid having to type in the full path to the data file we wish to load, we can set the working directory before we start work:
setwd("D:\\TEMP")
dat <- read.table(x = "mydata.csv", header = TRUE, sep = ",")
An alternative to reading data into R in as a file, we can copy and paste using the scan() function. Copy the data from a spreadsheet (for example) to the clipboard. In R, type:
dat <- scan()
A 1: will appear on the R console which means that R is ready to accept the data. Paste the data (CTL-V) into the R console and again hit <ENTER>. The object dat will comprise the pasted data. If you want to copy several (named) columns from a spreadsheet into R use:
read.table(x = "clipboard", sep = "\t", header = TRUE)
When your data is stored in a database you can import it into R using an ODBC connection. This is especially useful for large data sets. You will need to install the RODBC package first. If an error message is generated when you use the odbcConnectAccess2007 function switch to using the 32-bit version of R.
library(RODBC)
setwd("D:\\TEMP")
channel <- odbcConnectAccess2007("mydata.accdb")
dat <- sqlFetch(channel = channel, sqtable = "qData")
close(channel)
An alternative is to specify the content of the SQL query directly into R:
myqry <- paste(" SELECT * FROM Uk_stock")
channel <- odbcConnectAccess2007("mydata.accdb")
dat <- sqlQuery(channel, myqry)
close(channel)
*.RData files written using the save function can be read back into R using the load function. This approach is useful when you have a number of data objects that you want to restore into R at once:
load("mydata.RData")
The function write(x, file = "data.txt") writes an object x (a vector, a matrix, or an array) to the file data.txt. The function write.table() writes a data frame object to a file. For example:
setwd("D:\\TEMP")
write.table(x, file = "mydata.out", append = FALSE, quote = TRUE, sep = " ", row.names = FALSE, col.names = TRUE)
To save a group of objects to a file in R's own (binary) format, use:
save(list = c(dat01, dat02), file = "mydata.RData", ascii = TRUE)
Graphs can be saved in various image formats using the savePlot function.
setwd("D:\\TEMP")
x <- runif(n = 100, min = 0, max = 1)
y <- runif(n = 100, min = 0, max = 1)
plot(x, y, pch = 16)
savePlot(filename = "mygraph.png", type = c("png"), device = dev.cur())