1 #!/usr/local/bin/R
 2 
 3 # Xavier Fernández i Marín 
 4 # February 2007
 5 # http://xavier-fim.net
 6 
 7 # This script is only an example of the way we can import and export data with R
 8 
 9 
10 ### Import and export of data from text files (ASCII, txt, csv)
11 
12 # First, create some artificial data to export
13 data.to.export <- data.frame(a=rnorm(10), b=rnorm(10, 3), row.names=1:10)
14 
15 # Export the table to be used with spreadsheets or other programs
16 write.table(data.to.export, file="file.csv", sep=";")
17 
18 
19 # To import again this data, simply use
20 read.table(file="file.csv", sep=";")
21 
22 # Or, if you want to put it in a data.frame called 'data'
23 data <- read.table(file="file.csv", sep=";")
24 
25 
26 
27 ### From spreadsheets (like OpenOffice Calc, Microsoft Excel, etc...)
28 #   save the sheet as .csv or 'comma separated values' and remember with
29 #   character you have used to separate columns (variables)
30 #   Supose that the file is 'file.csv'.
31 
32 # The next example will work to import file called 'file.csv', which is a text
33 # file that uses ';' to separate columns, and its first row is the header.
34 data <- read.table("file.csv", sep=";", header=T)
35 
36 
37 
38 ### From other statistical software
39 #   To import (and, in some cases, export) data with other statistical packages
40 #   such are SPSS, Stata, SAS, we have to load the package called 'foreign'. As
41 #   it does not come with the standard installation we will have to install it
42 #   before we can continue
43 library(foreign)
44 help(package="foreign")  # to see what the options of 'foreign' are
45 
46 # Next command reads the file 'file_in_spss_format.sav' into a data frame that
47 # will be called 'data.from.spss'.
48 data.from.spss <- read.spss("file.sav", to.data.frame=T)
49 
50 
51 # Next command reads the file 'file_in_stata_format.dta' into a data frame that
52 # will be called 'data.from.stata'.
53 data.from.stata <- read.dta("file.dta")
54 
55 # Next command will create a stata file called 'file_in_stata_format.dta' with
56 # the contents of our data frame called 'data'.
57 write.dta(data, file="file_in_stata_format.dta")
58