#!/usr/local/bin/R

# Xavier Fernández i Marín 
# February 2007
# http://xavier-fim.net

# This script is only an example of the way we can import and export data with R


### Import and export of data from text files (ASCII, txt, csv)

# First, create some artificial data to export
data.to.export <- data.frame(a=rnorm(10), b=rnorm(10, 3), row.names=1:10)

# Export the table to be used with spreadsheets or other programs
write.table(data.to.export, file="file.csv", sep=";")


# To import again this data, simply use
read.table(file="file.csv", sep=";")

# Or, if you want to put it in a data.frame called 'data'
data <- read.table(file="file.csv", sep=";")



### From spreadsheets (like OpenOffice Calc, Microsoft Excel, etc...)
#   save the sheet as .csv or 'comma separated values' and remember with
#   character you have used to separate columns (variables)
#   Supose that the file is 'file.csv'.

# The next example will work to import file called 'file.csv', which is a text
# file that uses ';' to separate columns, and its first row is the header.
data <- read.table("file.csv", sep=";", header=T)



### From other statistical software
#   To import (and, in some cases, export) data with other statistical packages
#   such are SPSS, Stata, SAS, we have to load the package called 'foreign'. As
#   it does not come with the standard installation we will have to install it
#   before we can continue
library(foreign)
help(package="foreign")  # to see what the options of 'foreign' are

# Next command reads the file 'file_in_spss_format.sav' into a data frame that
# will be called 'data.from.spss'.
data.from.spss <- read.spss("file.sav", to.data.frame=T)


# Next command reads the file 'file_in_stata_format.dta' into a data frame that
# will be called 'data.from.stata'.
data.from.stata <- read.dta("file.dta")

# Next command will create a stata file called 'file_in_stata_format.dta' with
# the contents of our data frame called 'data'.
write.dta(data, file="file_in_stata_format.dta")