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 ofread.table()
.The command is:
- Example: lets write the mydat object to the file
write.datatest.txt
:
5.2 Variants of write.table()
- Useful variants of
write.table
are:write.csv()
: comma separated, dot as decimal pointwrite.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
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
dget()
inversesdput()
: note that thedget()
command below doesn’t restore lis, but creates an object similar to lis, which can be assigned to other objects:
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: