Los datos y comandos en R

Aquí se definen parámetros generales y el espacio de trabajo

options(max.print = 100000, width=300)                                          # dimensiones salida
getwd()                                                                         # donde estamos ahora
## [1] "/home/sergio/Documents/Lavoro in corso/Análisis de datos y estadística inferencial - IMCA/Lezioni 2024/Clase_2/R"
setwd("~/Documents/Lavoro in corso/Análisis de datos y estadística inferencial - IMCA/Lezioni 2024/Clase_2/R")                                                                # donde vamos

Uso de for y de if

x = c(5,2,0,-3,7)
y = 6
y/sqrt(x)
## Warning in sqrt(x): NaNs produced
## [1] 2.683282 4.242641      Inf      NaN 2.267787
for (i in 1:length(x)) {
  if (x[i] > 0) {
    print (y/sqrt(x[i]))
  } else if (x[i] == 0) {
    print(paste("x = ",x[i],": division by zero illegal", sep="")) 
  } else {
    print(paste("x = ",x[i],": square root of negative x is illegal"))
  } 
}
## [1] 2.683282
## [1] 4.242641
## [1] "x = 0: division by zero illegal"
## [1] "x =  -3 : square root of negative x is illegal"
## [1] 2.267787

Importación de archivos

Se pueden importar archivos .csv, o sea separando los datos con comma, así como archivos salidos de hojas electrónicas, como .ods (de Libre Office calc), .xls y .xlsx (de Microsoft Excel).

Los archivos .csv se colgan con los comandos read.csv(), si los datos son separados para comas y el decimal es un punto; con read.csv2() si son separados para punto y coma y el decimal es un coma.

Funcionan también para bajar datos desde internet.

piel<-read.csv("Pielescuero.csv", header = TRUE); head(piel)
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
read.csv("Pielescuero.csv",header=TRUE, sep = ",", quote="", dec=".")
##     X.Exportacion. X.Tamano. X.Financiacion. X.Zona. X.Actividad.
## 1                1         1               2       2            4
## 2                2         1               2       3            3
## 3                1         1               2       2            3
## 4                1         1               2       2            3
## 5                1         1               2       1            3
## 6                1         1               2       3            3
## 7                1         1               2       3            3
## 8                1         1               2       3            3
## 9                1         1               2       1            4
## 10               2         1               2       1            3
## 11               2         1               2       1            4
## 12               2         1               2       1            3
## 13               1         1               1       1            3
## 14               1         1               2       1            3
## 15               2         2               1       3            3
## 16               2         2               2       1            3
## 17               2         2               1       1            4
## 18               1         2               2       1            3
## 19               1         2               2       1            3
## 20               2         2               1       2            3
## 21               1         2               1       2            3
## 22               2         2               1       3            4
## 23               2         2               1       3            3
## 24               2         2               2       3            4
## 25               1         2               2       1            3
## 26               1         2               2       1            3
## 27               2         2               2       1            4
## 28               1         2               2       3            3
## 29               1         2               2       3            3
## 30               1         2               1       3            3
## 31               1         2               1       3            3
## 32               2         2               2       3            3
## 33               2         2               2       3            3
## 34               1         2               2       3            3
## 35               1         2               1       3            3
## 36               1         2               2       3            3
## 37               1         2               2       2            3
## 38               1         2               2       2            3
## 39               1         2               1       2            3
## 40               1         2               1       1            3
## 41               2         2               2       1            3
## 42               1         2               2       1            4
## 43               2         2               1       3            4
## 44               2         2               1       3            3
## 45               1         2               2       2            3
## 46               2         2               2       2            3
## 47               2         2               1       2            3
## 48               1         2               2       2            4
## 49               1         2               1       2            3
## 50               2         3               2       2            4
## 51               1         3               1       2            3
## 52               2         3               2       2            3
## 53               1         3               2       1            3
## 54               1         3               2       3            3
## 55               2         3               2       1            3
## 56               1         3               1       2            3
## 57               1         3               2       1            3
## 58               1         3               1       3            3
## 59               1         3               1       3            3
## 60               2         3               1       3            3
## 61               1         3               1       3            3
## 62               1         3               1       2            3
## 63               2         3               2       3            3
## 64               1         3               1       3            3
## 65               2         3               2       2            3
## 66               2         1               2       3            1
## 67               1         1               2       3            1
## 68               1         1               2       3            1
## 69               1         1               1       3            1
## 70               2         1               2       3            1
## 71               1         1               2       3            1
## 72               2         1               2       3            1
## 73               1         1               1       3            2
## 74               1         1               2       3            1
## 75               1         1               2       3            2
## 76               2         1               2       3            1
## 77               1         1               2       3            1
## 78               1         1               2       2            2
## 79               1         1               2       1            1
## 80               1         1               2       1            1
## 81               1         1               2       2            2
## 82               1         1               2       3            2
## 83               1         1               2       3            2
## 84               2         1               1       3            2
## 85               1         1               2       3            2
## 86               1         1               2       3            2
## 87               2         1               2       2            2
## 88               1         1               2       2            2
## 89               1         1               2       2            2
## 90               1         1               1       2            2
## 91               1         1               2       1            1
## 92               1         1               2       1            1
## 93               2         1               2       1            1
## 94               1         1               2       3            1
## 95               2         1               2       3            1
## 96               2         1               2       3            1
## 97               2         1               1       3            1
## 98               1         1               2       3            1
## 99               1         1               2       3            1
## 100              1         1               2       3            2
## 101              2         1               2       3            1
## 102              1         1               2       1            1
## 103              2         1               2       3            2
## 104              1         1               2       3            2
## 105              1         2               2       3            1
## 106              1         2               1       3            1
## 107              1         2               2       1            1
## 108              1         2               2       1            2
## 109              1         2               2       1            1
## 110              1         2               1       1            2
## 111              1         2               1       1            2
## 112              1         2               1       1            2
## 113              1         2               2       1            2
## 114              2         2               2       2            2
## 115              1         2               2       2            2
## 116              2         2               2       3            1
## 117              1         2               1       3            2
## 118              1         2               2       3            1
## 119              1         2               1       3            1
## 120              1         2               2       3            2
## 121              1         2               2       3            1
## 122              1         2               1       2            2
## 123              1         2               1       2            1
## 124              1         2               2       2            1
## 125              1         2               2       2            1
## 126              2         2               2       3            2
## 127              1         2               1       3            2
## 128              1         2               1       3            2
## 129              1         2               1       3            1
## 130              1         2               2       3            1
## 131              2         2               1       3            1
## 132              1         2               2       1            2
## 133              1         2               2       1            2
## 134              2         2               2       3            2
## 135              1         2               2       3            2
## 136              1         2               2       3            2
## 137              1         2               1       3            2
## 138              1         2               1       3            1
## 139              1         2               2       3            2
## 140              1         2               2       3            1
## 141              1         2               2       3            2
## 142              1         2               2       3            2
## 143              2         2               2       3            2
## 144              1         2               2       3            2
## 145              1         2               2       3            2
## 146              1         2               2       3            2
## 147              1         2               2       3            2
## 148              1         2               2       3            2
## 149              1         2               1       3            2
## 150              1         2               1       3            2
## 151              1         2               2       3            2
## 152              1         2               1       2            2
## 153              1         2               2       2            2
## 154              1         2               2       2            2
## 155              1         2               2       2            2
## 156              1         2               1       2            2
## 157              1         2               2       2            2
## 158              1         2               2       2            2
## 159              1         2               1       1            1
## 160              1         2               2       1            1
## 161              1         2               1       1            1
## 162              1         2               2       1            1
## 163              1         3               2       1            2
## 164              2         3               2       3            1
## 165              1         3               1       2            1
## 166              1         3               2       2            2
## 167              1         3               2       1            2
## 168              1         3               1       3            2
## 169              1         3               2       3            2
## 170              1         3               1       2            2
## 171              1         3               2       2            1
## 172              1         3               1       1            2
## 173              1         3               2       1            2
piel<-read.csv("http://www.camiz.it/Universita/Dati/Pielescuero.csv", header = TRUE); head(piel)
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-read.csv("http://www.camiz.it/Universita/Dati/Pielescuero2.csv", header = TRUE); head(piel)
##   Exportaciones.Tamano.Financiacion.Zona.Actividad
## 1                                        1;1;2;2;4
## 2                                        2;1;2;3;3
## 3                                        1;1;2;2;3
## 4                                        1;1;2;2;3
## 5                                        1;1;2;1;3
## 6                                        1;1;2;3;3

Nótese la mala lectura en este caso, corregida para read.csv2()

piel<-read.csv2("http://www.camiz.it/Universita/Dati/Pielescuero2.csv", header = TRUE); head(piel)
##   Exportaciones Tamano Financiacion Zona Actividad
## 1             1      1            2    2         4
## 2             2      1            2    3         3
## 3             1      1            2    2         3
## 4             1      1            2    2         3
## 5             1      1            2    1         3
## 6             1      1            2    3         3
#  con separador ";" y decimal ","  
piel<-read.csv2("Pielescuero2.csv", header = TRUE,quote=""); head(piel)
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3

Por los archivos de hojas electrónicas se necesitan paquetes particulares. Para los archivos .ods se necesita readODS.

# importación de archivos libre office calc .ods
library(readODS)         # libraria necesaria
piel<-read_ods("Pielescuero.ods",sheet="Datos"); head(piel) 
## # A tibble: 6 × 5
##   Exportacion Tamano Financiacion  Zona Actividad
##         <dbl>  <dbl>        <dbl> <dbl>     <dbl>
## 1           1      1            2     2         4
## 2           2      1            2     3         3
## 3           1      1            2     2         3
## 4           1      1            2     2         3
## 5           1      1            2     1         3
## 6           1      1            2     3         3
# piel<-read_ods("http://www.camiz.it/Universita/Dati/Pielescuero.ods",sheet="Datos"); head(piel) 

que pero no funciona con internet.

Para los archivos de Excel sirve el paquete readxl

# importación de archivos excel 
library(readxl)
piel<-read_excel("Pielescuero.xls",sheet="Datos"); head(piel) 
## # A tibble: 6 × 5
##   Exportacion Tamano Financiacion  Zona Actividad
##         <dbl>  <dbl>        <dbl> <dbl>     <dbl>
## 1           1      1            2     2         4
## 2           2      1            2     3         3
## 3           1      1            2     2         3
## 4           1      1            2     2         3
## 5           1      1            2     1         3
## 6           1      1            2     3         3
piel<-read_excel("Pielescuero.xlsx",sheet="Datos"); head(piel) 
## # A tibble: 6 × 5
##   Exportacion Tamano Financiacion  Zona Actividad
##         <dbl>  <dbl>        <dbl> <dbl>     <dbl>
## 1           1      1            2     2         4
## 2           2      1            2     3         3
## 3           1      1            2     2         3
## 4           1      1            2     2         3
## 5           1      1            2     1         3
## 6           1      1            2     3         3
# piel<-read_excel("http://www.camiz.it/Universita/Dati/Pielescuero.xls",sheet="Datos"); head(piel) 
# piel<-read_excel("http://www.camiz.it/Universita/Dati/Pielescuero.xlsx",sheet="Datos"); head(piel)

que no funciona en internet.

Para lo archivos .xslx se puede emplear también el paquete opnxlsx,

# 
library(openxlsx)
piel<-read.xlsx("Pielescuero.xlsx",sheet="Datos"); head(piel) 
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-read.xlsx("http://www.camiz.it/Universita/Dati/Pielescuero.xlsx",sheet="Datos"); head(piel) 
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
# piel<-read.xlsx("Pielescuero.xls",sheet="Datos"); head(piel) 

que funciona en internet pero no funcione con el viejo formado .xls.

La función import() del paquete rio funciona en todos casos

# posibilidad para todos
library(rio)
piel<-import("Pielescuero.ods",sheet="Datos"); head(piel) 
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-import("http://www.camiz.it/Universita/Dati/Pielescuero.ods",sheet="Datos"); head(piel) 
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-import("Pielescuero.xls",sheet="Datos"); head(piel) 
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-import("http://www.camiz.it/Universita/Dati/Pielescuero.xlsx",sheet="Datos"); head(piel) 
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-import("Pielescuero2.csv", header = TRUE); head(piel)
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-import("http://www.camiz.it/Universita/Dati/Pielescuero.csv", header = TRUE); head(piel)
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
piel<-import("Pielescuero2.csv", header = TRUE); head(piel)
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3

Una vez colgado un archivo, para conocer la estructura del archivo, hay varios comandos

typeof(piel)                # tipo de estructura
## [1] "list"
str(piel)                   # composición de la estructura
## 'data.frame':    173 obs. of  5 variables:
##  $ Exportacion : int  1 2 1 1 1 1 1 1 1 2 ...
##  $ Tamano      : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ Financiacion: int  2 2 2 2 2 2 2 2 2 2 ...
##  $ Zona        : int  2 3 2 2 1 3 3 3 1 1 ...
##  $ Actividad   : int  4 3 3 3 3 3 3 3 4 3 ...
dim(piel)                   # dimensiones (array y data frames) 
## [1] 173   5
rownames(piel)              # nombres de filas
##   [1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"   "9"   "10"  "11"  "12"  "13"  "14"  "15"  "16"  "17"  "18"  "19"  "20"  "21"  "22"  "23"  "24"  "25"  "26"  "27"  "28"  "29"  "30"  "31"  "32"  "33"  "34"  "35"  "36"  "37"  "38"  "39"  "40"  "41"  "42"  "43"  "44"  "45"  "46"  "47"  "48"  "49" 
##  [50] "50"  "51"  "52"  "53"  "54"  "55"  "56"  "57"  "58"  "59"  "60"  "61"  "62"  "63"  "64"  "65"  "66"  "67"  "68"  "69"  "70"  "71"  "72"  "73"  "74"  "75"  "76"  "77"  "78"  "79"  "80"  "81"  "82"  "83"  "84"  "85"  "86"  "87"  "88"  "89"  "90"  "91"  "92"  "93"  "94"  "95"  "96"  "97"  "98" 
##  [99] "99"  "100" "101" "102" "103" "104" "105" "106" "107" "108" "109" "110" "111" "112" "113" "114" "115" "116" "117" "118" "119" "120" "121" "122" "123" "124" "125" "126" "127" "128" "129" "130" "131" "132" "133" "134" "135" "136" "137" "138" "139" "140" "141" "142" "143" "144" "145" "146" "147"
## [148] "148" "149" "150" "151" "152" "153" "154" "155" "156" "157" "158" "159" "160" "161" "162" "163" "164" "165" "166" "167" "168" "169" "170" "171" "172" "173"
colnames(piel)              # nombres de columnas
## [1] "Exportacion"  "Tamano"       "Financiacion" "Zona"         "Actividad"
piel<-read.csv("Pielescuero.csv"); head(piel)     # lectura de Pielescuero
##   Exportacion Tamano Financiacion Zona Actividad
## 1           1      1            2    2         4
## 2           2      1            2    3         3
## 3           1      1            2    2         3
## 4           1      1            2    2         3
## 5           1      1            2    1         3
## 6           1      1            2    3         3
typeof(piel); dim(piel)
## [1] "list"
## [1] 173   5

Tratamiento de factores

Cada factor tiene que ser declarado por su mismo. Es conveniente, antes, de copiar todo el data frame en otro objeto y conectarlo con attach() para simplificar el trabajo. Aquí el tratamiento por todos los datos de pielescuero.

pielc <- piel                                     # copia sobre otro data frame
attach(pielc)

pielc$Exportacion  <- factor(piel$Exportacion,
                             levels = c(1,2),
                             labels = c("siexp","noexp")) 
pielc$Tamano       <- factor(piel$Tamano,
                             levels = c(1,2,3),
                             labels = c("11-20","21-50","> 50"), ordered = TRUE) 
pielc$Financiacion <- factor(piel$Financiacion,
                             levels = c(1,2),
                             labels = c("sipre","nopre")) 
pielc$Zona         <- factor(piel$Zona,
                             levels = c(1,2,3),
                             labels = c("NO","NE","CE")) 
pielc$Actividad    <- factor(piel$Actividad,
                             levels = c(1,2,3,4),
                             labels = c("PeCu","Zapa","Ropa","MeAl")) 
head(pielc); typeof(pielc); str(pielc); summary(pielc)
##   Exportacion Tamano Financiacion Zona Actividad
## 1       siexp  11-20        nopre   NE      MeAl
## 2       noexp  11-20        nopre   CE      Ropa
## 3       siexp  11-20        nopre   NE      Ropa
## 4       siexp  11-20        nopre   NE      Ropa
## 5       siexp  11-20        nopre   NO      Ropa
## 6       siexp  11-20        nopre   CE      Ropa
## [1] "list"
## 'data.frame':    173 obs. of  5 variables:
##  $ Exportacion : Factor w/ 2 levels "siexp","noexp": 1 2 1 1 1 1 1 1 1 2 ...
##  $ Tamano      : Ord.factor w/ 3 levels "11-20"<"21-50"<..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ Financiacion: Factor w/ 2 levels "sipre","nopre": 2 2 2 2 2 2 2 2 2 2 ...
##  $ Zona        : Factor w/ 3 levels "NO","NE","CE": 2 3 2 2 1 3 3 3 1 1 ...
##  $ Actividad   : Factor w/ 4 levels "PeCu","Zapa",..: 4 3 3 3 3 3 3 3 4 3 ...
##  Exportacion   Tamano   Financiacion Zona    Actividad
##  siexp:129   11-20:53   sipre: 53    NO:43   PeCu:46  
##  noexp: 44   21-50:93   nopre:120    NE:42   Zapa:62  
##              > 50 :27                CE:88   Ropa:54  
##                                              MeAl:11

Es importante acuerdar que, si se guarda el data frame en un archivo externo, luego la estructura de factores se pierde.

write.csv(pielc,file="Pielescuero_car.csv",row.names=FALSE)
pielet <- read.csv("Pielescuero_car.csv"); head(pielet)
##   Exportacion Tamano Financiacion Zona Actividad
## 1       siexp  11-20        nopre   NE      MeAl
## 2       noexp  11-20        nopre   CE      Ropa
## 3       siexp  11-20        nopre   NE      Ropa
## 4       siexp  11-20        nopre   NE      Ropa
## 5       siexp  11-20        nopre   NO      Ropa
## 6       siexp  11-20        nopre   CE      Ropa
str(pielet)
## 'data.frame':    173 obs. of  5 variables:
##  $ Exportacion : chr  "siexp" "noexp" "siexp" "siexp" ...
##  $ Tamano      : chr  "11-20" "11-20" "11-20" "11-20" ...
##  $ Financiacion: chr  "nopre" "nopre" "nopre" "nopre" ...
##  $ Zona        : chr  "NE" "CE" "NE" "NE" ...
##  $ Actividad   : chr  "MeAl" "Ropa" "Ropa" "Ropa" ...

nótese que la estructura de factores se ha perdido.