Introduction to R - Introduzione a R
Read data from a text file
First of all verify how data are organized in the text file: is there a column header? which is the field separator (space, ",", ";")? which is the decimal delimiter (".", ",")? once these questions are answered we are ready to load data from a file present in the working directory
> dat=read.table("iris.txt",header=T,dec=".")
This data le contains the famous (Fisher's or Anderson's) iris data set, with the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.
> dat1=read.table("iris.csv",header=T,sep=";")
using
> ?read.table
we can see all the options available to read text formatted data. to import data from databases (access, mysql etc.) there exist several packages such as RODBC (it connects to most existing databases including excel), foreign (to read .dbf, SAS, SPSS, Matlab and more).
> str(dat)
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
this function compactly displays the internal structure of an R object while
> summary(dat)
| Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | ||||||||||
| Min. : | 4.300 | Min. : | 2.000 | Min. : | 1.000 | Min. : | 0.100 | setosa : | 50 | |||||
| 1st Qu.: | 5.100 | 1st Qu.: | 2.800 | 1st Qu.: | 1.600 | 1st Qu.: | 0.300 | versicolor: | 50 | |||||
| Median : | 5.800 | Median : | 3.000 | Median : | 4.350 | Median : | 1.300 | virginica : | 50 | |||||
| Mean : | 5.843 | Mean : | 3.057 | Mean : | 3.758 | Mean : | 1.199 | |||||||
| 3rd Qu.: | 6.400 | 3rd Qu.: | 3.300 | 3rd Qu.: | 5.100 | 3rd Qu.: | 1.800 | |||||||
| Max. : | 7.900 | Max. : | 4.400 | Max. : | 6.900 | Max. : | 2.500 |
it returns basic statistics from the columns of the object dat. summary is a generic function that applied to R objects returns summary information on the object content depending on the object class. R objects belong to classes and most generic functions have a specific behaviour for each class. To asses an object class use the function class(). The mode function tells what type of data we have and the class function tells which special methods are available for that object. For example to mode(iris) returns list, while class(iris) returns data.frame.
> class(dat)
[1] "data.frame"
a data frame is like a simple spreadsheet where different types of information may live together. To see its dimensions type
> dim(dat)
[1] 150 5
dat has 150 rows and 5 columns (equivalently nrow(dat) and ncol(dat)), all columns in a dataframe must have the same number of rows, when a cell is empty it is assumed to be missing and denoted with NA
> dat2=read.table("irisNA.csv",header=T,sep=";")
> summary(dat2)
| Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | ||||||||||
| Min. : | 4.300 | Min. : | 2.000 | Min. : | 1.000 | Min. : | 0.100 | setosa : | 50 | |||||
| 1st Qu.: | 5.100 | 1st Qu.: | 2.800 | 1st Qu.: | 1.600 | 1st Qu.: | 0.300 | versicolor: | 50 | |||||
| Median : | 5.800 | Median : | 3.000 | Median : | 4.350 | Median : | 1.300 | virginica : | 50 | |||||
| Mean : | 5.843 | Mean : | 3.057 | Mean : | 3.758 | Mean : | 1.199 | |||||||
| 3rd Qu.: | 6.400 | 3rd Qu.: | 3.300 | 3rd Qu.: | 5.100 | 3rd Qu.: | 1.800 | |||||||
| Max. : | 7.900 | Max. : | 4.400 | Max. : | 6.900 | Max. : | 2.500 | |||||||
| NA's | 1 | NA's | 1 | NA's | 1 | NA's | 1 |
Missing data influence results of statistical functions unless we specify what the function should do with the missing, for example:
> mean(dat2[,1])
[1] NA
> mean(dat2[,1],na.rm=T)
[1] 5.841611
Leggere dati da un file di testo
Per prima cosa si verifica come é strutturato il file di testo:
- Ci sono intestazioni di colonna?
- Quale é il separatore di pagina (spazio, ",", ";")?
- Quale é il delimitatore decimale (".", ",")?
Una volta individuata la struttura si possono caricare i dati dal file nella cartella di lavoro
> dat=read.table("iris.txt",header=T,dec=".")
Questi dati si riferiscono al fomoso data set dell'Iris (Fisher's or Anderson's), con le misure in centimetri della lunghezza e larghezza dei sepali e dei petali rispettivamente, per 50 fiori di ciscuna delle 3 specie dell'iris. Le specie sono Iris setosa, versicolor, e virginica.
> dat1=read.table("iris.csv",header=T,sep=";")
usando
> ?read.table
si vedono tutte le opzioni disponibile per la lettura di dati di testo formattato. Per importare dati di database (access, mysql, ecc.) ci sono diversi pacchetti come il pacchetto RODBC (che permette la connessione a database esistenti compreso excel), esterni (per leggere .dbf, SAP, SPSS, Matlab e altri).
> str(dat)
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
questa funzione (str()) visualizza in forma compatta la struttura di un oggetto di R (dat), mentre
> summary(dat)
| Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | ||||||||||
| Min. : | 4.300 | Min. : | 2.000 | Min. : | 1.000 | Min. : | 0.100 | setosa : | 50 | |||||
| 1st Qu.: | 5.100 | 1st Qu.: | 2.800 | 1st Qu.: | 1.600 | 1st Qu.: | 0.300 | versicolor: | 50 | |||||
| Median : | 5.800 | Median : | 3.000 | Median : | 4.350 | Median : | 1.300 | virginica : | 50 | |||||
| Mean : | 5.843 | Mean : | 3.057 | Mean : | 3.758 | Mean : | 1.199 | |||||||
| 3rd Qu.: | 6.400 | 3rd Qu.: | 3.300 | 3rd Qu.: | 5.100 | 3rd Qu.: | 1.800 | |||||||
| Max. : | 7.900 | Max. : | 4.400 | Max. : | 6.900 | Max. : | 2.500 |
restituisce statistiche di base delle colonne dell'oggetto dat. summary() é una funzione generica che restituisce informazioni di riepilogo di un oggetto di R. Le informazioni dipendono dalla classe dell'oggetto. Gli oggetti di R appartengono a classi e le funzioni piú generiche hanno un comportamento specifico a per ogni classe per determinare la classe di un oggetto si usa la funzione class().
La funzione mode() restituisce il tipo di dato e la funzione class() indica quali metodi speciali sono disponibili per quell'oggetto. Per esempio mode(iris) restituisce list, mentre class(iris) restituisce data.frame.
> class(dat)
[1] "data.frame"
un dataframe é come un foglio elettronico, in cui convivono diversi tipi di informazioni. Per recuperarne le dimensioni:
> dim(dat)
[1] 150 5
dat presenta 150 righe e 5 colonne (equivalente a nrow(dat) e ncol(dat)), tutte le colonne in un dataframe devono avere lo stesso numero di righe, se una cella é vuota si presume che il dato manca e viene indicato con NA
> dat2=read.table("irisNA.csv",header=T,sep=";")
> summary(dat2)
| Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | ||||||||||
| Min. : | 4.300 | Min. : | 2.000 | Min. : | 1.000 | Min. : | 0.100 | setosa : | 50 | |||||
| 1st Qu.: | 5.100 | 1st Qu.: | 2.800 | 1st Qu.: | 1.600 | 1st Qu.: | 0.300 | versicolor: | 50 | |||||
| Median : | 5.800 | Median : | 3.000 | Median : | 4.350 | Median : | 1.300 | virginica : | 50 | |||||
| Mean : | 5.843 | Mean : | 3.057 | Mean : | 3.758 | Mean : | 1.199 | |||||||
| 3rd Qu.: | 6.400 | 3rd Qu.: | 3.300 | 3rd Qu.: | 5.100 | 3rd Qu.: | 1.800 | |||||||
| Max. : | 7.900 | Max. : | 4.400 | Max. : | 6.900 | Max. : | 2.500 | |||||||
| NA's | 1 | NA's | 1 | NA's | 1 | NA's | 1 |
Dati mancanti influenza i risultati di funzioni statistiche, a meno che non si specifica nella funzione cosa fare con i dati mancanti, per esempio:
> mean(dat2[,1])
[1] NA
> mean(dat2[,1],na.rm=T)
[1] 5.841611