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
- 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: