5 Writing data to files

5.1 Writing data to a text file

  • Just like data import, data can be exported from R in many ways. You can export directly to:

    • Excel
    • SAS
    • SPSS
    • STATA
  • One package to use in case of SAS, SPSS and STATA is the foreign package.

  • Eg: data frame to be written:

> 
> # use scan() to import this data:
> 
> mydat <- data.frame(x1 = c(2, 2, 3, 3, 1, 1), x2 = c(0.3, 1, 2.1, 2.2, 0.1, 0.2),
+     x3 = c(0.01, 0.11, 0.04, 0.02, 0.1, 0.06))
> 
> # mydat<-data.frame(x1=scan(),x2=scan(),x3=scan())
> 
> mydat
##   x1  x2   x3
## 1  2 0.3 0.01
## 2  2 1.0 0.11
## 3  3 2.1 0.04
## 4  3 2.2 0.02
## 5  1 0.1 0.10
## 6  1 0.2 0.06
  • The function to use is write.table(), the reverse of read.table().

  • The command is:

> write.table(R_Object, file="filename.xyz", row.names=FALSE, sep=..., dec=..., ...)
  • Example: lets write the mydat object to the file write.datatest.txt:
> 
> # First, create the output folder
> 
> folder <- "OutFiles"
> if (file.exists(folder)) {
+     cat("The folder already exists!")
+ } else {
+     dir.create(folder)
+ }
## The folder already exists!
> 
> write.table(mydat, file = "OutFiles/write.datatest.txt", row.names = FALSE, sep = ";",
+     dec = ".")

5.2 Variants of write.table()

  • Useful variants of write.table are:
    • write.csv(): comma separated, dot as decimal point
    • write.csv2(): semicolon separated, comma as decimal point
> write.table(mydat, file = "OutFiles/write.datatest.csv", row.names = FALSE, sep = ";",
+     dec = ".")
  • Additional arguments are similar to those of write.table().

5.3 Basic writing functions

  • cat(): concatenate and print
> set.seed(832)
> cat("Some random numbers are:\n", rnorm(3), file = "OutFiles/cattest.txt")
  • writeLines(): write text lines
> lin <- c("Some", LETTERS[1:10], "for instance")
> writeLines(lin, con = "OutFiles/writelinestest.txt")
  • sink(): send R output to a file
> # CAUTION: THIS WILL ERASE ALL DATA
> rm(list = ls())
> 
> sink("OutFiles/sinktest.txt")
> x <- 1:10
> y <- x^2
> x + y
##  [1]   2   6  12  20  30  42  56  72  90 110
> sink()
  • dput(): write an object to a file
> lis <- list(x = 1:5, y = 3, z = c("a", "b", "c"))
> dput(lis, file = "OutFiles/dputtest.txt")
  • dget() inverses dput(): note that the dget() command below doesn’t restore lis, but creates an object similar to lis, which can be assigned to other objects:
> myobj <- dget("OutFiles/dputtest.txt")
> myobj
## $x
## [1] 1 2 3 4 5
## 
## $y
## [1] 3
## 
## $z
## [1] "a" "b" "c"

5.4 Working with binary files: using save() and load()

  • R also has its own internal binary.
  • To save data and functions to it use e.g:
> list.out <- list(a = rnorm(3), b = 1:5, c = "text text", d = matrix(round(rnorm(12),
+     8), ncol = 3))
> save(list.out, file = "OutFiles/test1.RData")
  • To read back into R simple use:
> # CAUTION: THIS WILL ERASE ALL DATA
> rm(list = ls())
> load(file = "OutFiles/test1.RData")
> ls()
## [1] "list.out"