0% found this document useful (0 votes)
64 views9 pages

Curso Básico de Iniciación A La Programación Con R Álvaro Mauricio Bustamante Lozano

This document provides an introduction to programming in R. It discusses various data types in R including vectors, matrices, factors, lists and missing data. It demonstrates how to create, subset and manipulate these objects. Various functions for combining and transforming data such as cbind(), rbind(), t() and dimnames are also illustrated through examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views9 pages

Curso Básico de Iniciación A La Programación Con R Álvaro Mauricio Bustamante Lozano

This document provides an introduction to programming in R. It discusses various data types in R including vectors, matrices, factors, lists and missing data. It demonstrates how to create, subset and manipulate these objects. Various functions for combining and transforming data such as cbind(), rbind(), t() and dimnames are also illustrated through examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Curso básico de iniciación a la programación con R

Álvaro Mauricio Bustamante Lozano.

# Atributos, entrada y coerción


> x<-5
> x
[1] 5
> #Vector de números
> x<- 1:100
> x
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1
7 18 19 20
[21] 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
37 38 39 40
[41] 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
77 78 79 80
[81] 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
97 98 99 100
> #Vectores de objetos c()
> #Vector numérico
> x<- c(0.3, 0.9)
> x
[1] 0.3 0.9
> x<- c(1, 5, 6 , 8 ,2, 6 , 9, 4,3)
> x
[1] 1 5 6 8 2 6 9 4 3
> #vector lógico
> x<-c(TRUE, FALSE, FALSE, TRUE)
> x
[1] TRUE FALSE FALSE TRUE
> # Caracteres
> x<- c("a", "b", "d", "t")
> x
[1] "a" "b" "d" "t"
> # Vector complejo
> x<- c(1+0i, 2+4i, 3+6i)
> x
[1] 1+0i 2+4i 3+6i
> #Usando la instrucción vector
> x<- vector("numeric", length = 10)
> x
[1] 0 0 0 0 0 0 0 0 0 0
> x<- 1:100
> class(x)
[1] "integer"
> #matrices
> #Función matrix
> m<- matrix(1:6, nrow = 2, ncol = 3)
> m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> dim(m)
[1] 2 3
> #Instrucción dim
> m<- 1:10
> m
[1] 1 2 3 4 5 6 7 8 9 10
> dim(m) <- c(2,5)
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> d<- 1:20
> dim(d) <- c(4,5)
> d
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
> #Función cbind y rbind
> x<-5:8
> y<-12:15
> cbind(x,y)
x y
[1,] 5 12
[2,] 6 13
[3,] 7 14
[4,] 8 15
> rbind(x,y)
[,1] [,2] [,3] [,4]
x 5 6 7 8
y 12 13 14 15
> #Operaciones vectoriales y reglas de procedencia
> ?base:sintax
> x<-7:10
> y<-9:12
> x+y
[1] 16 18 20 22
> x>8
[1] FALSE FALSE TRUE TRUE
> y==11
[1] FALSE FALSE TRUE FALSE
> x*y
[1] 63 80 99 120
> x/y
[1] 0.7777778 0.8000000 0.8181818 0.8333333
> x<-matrix(1:16, 4, 4)
> y<-matrix(rep(5,16), 4,4)
> x
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
> y
[,1] [,2] [,3] [,4]
[1,] 5 5 5 5
[2,] 5 5 5 5
[3,] 5 5 5 5
[4,] 5 5 5 5
> x+y
[,1] [,2] [,3] [,4]
[1,] 6 10 14 18
[2,] 7 11 15 19
[3,] 8 12 16 20
[4,] 9 13 17 21
> x*y
[,1] [,2] [,3] [,4]
[1,] 5 25 45 65
[2,] 10 30 50 70
[3,] 15 35 55 75
[4,] 20 40 60 80
> x%%y
[,1] [,2] [,3] [,4]
[1,] 1 0 4 3
[2,] 2 1 0 4
[3,] 3 2 1 0
[4,] 4 3 2 1
matriz1 <- matrix(0,4,4)
matriz1 <- matrix(c(1:25),5,5,T)
matriz1

myarray = array(1:12, dim = c(2,3,4))


myarray

matriz1[1,2]

matriz1
matriz2 <- matrix(3,5,5)
matriz2
#Combinar matrices Cbind y rbind

matriz3 <- cbind(matriz1,matriz2)


matriz3

matriz4 <- rbind(matriz1,matriz2)


matriz4

t(matriz1) # transpuesta
diag(matriz1)
det(matriz1)
matriz1*matriz2
matriz1*34

#Resolver sistemas de ecuaciones lineales

# +x -3y +2z = -3
# +5x +6y -z = 13
# +4x -y +3z = 8

A = matrix(c(1,5,4,-3,6,-1,2,-1,3),3,3)
A
B = matrix(c(-3,13,8),3,1)
B
C <- solve(A,B)
C
#Listas, Factores, Valores faltantes
> #Vectores con distintos tipos de datos
> x<-list(1, "a", TRUE, 1+8i)
> x
[[1]]
[1] 1

[[2]]
[1] "a"
[[3]]
[1] TRUE

[[4]]
[1] 1+8i

> #Los factores son untipo especial de vectores, usado para representa
e datos categóricos
> x<-factor(c("yes", "yes", "no"))
> x
[1] yes yes no
Levels: no yes
> x<-(c("Futbol", "ciclismo", "Futbol", "Boxeo", "Futbol", "Boxeo", "c
iclismo"))
>
> x
[1] "Futbol" "ciclismo" "Futbol" "Boxeo" "Futbol" "Boxeo"
"ciclismo"
> table(x)
x
Boxeo ciclismo Futbol
2 2 3
> unclass(x)
[1] "Futbol" "ciclismo" "Futbol" "Boxeo" "Futbol" "Boxeo"
"ciclismo"
> x<-factor(c("si", "no", "no"), levels = c("si","no"))
> x
[1] si no no
Levels: si no
> #Datos faltantes
> x<-c(5, 6, NA, 9, 10)
> is.nan(x)
[1] FALSE FALSE FALSE FALSE FALSE
> is.na(x)
[1] FALSE FALSE TRUE FALSE FALSE
is.na(x)
[1] FALSE FALSE TRUE TRUE FALSE FALSE
> x<-data.frame(columna1 = 1:4, columna2 = c(T, T, T, F))
> x
columna1 columna2
1 1 TRUE
2 2 TRUE
3 3 TRUE
4 4 FALSE
> m<-matrix(1:15, nrow= 5, ncol = 3)
> dimnames <- list(c("a", "b", "c", "d", "e"), c("e", "f", "g"))
> m
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
> dimnames <- list(c("a", "b", "c", "d", "e"), c("f", "g", "h"))
> m
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
> dimnames <- list(c("f", "g", "h"), c("a", "b", "c", "d", "e"))
> m
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
> dimnames <- list(c("f", "g", "h"), c("a", "b", "j", "d", "e"))
> m
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
> dimnames <- list(c("a", "b", "j", "d", "e"), c("f", "g", "h"))
> m
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
> m<-matrix(1:4, nrow = 2, ncol =2)
> dimnames<-list(c("a", "b"), c("h", "i"))
> m
[,1] [,2]
[1,] 1 3
[2,] 2 4
> dimnames<-list(c("a","b"), c("h","i"))
> m
[,1] [,2]
[1,] 1 3
[2,] 2 4
> #Extraer elementos
> x<-c("a", "b", "c", "d", "a")
> x[3]
[1] "c"
> x[1]
[1] "a"
> x[1:5]
[1] "a" "b" "c" "d" "a"
> x[x>"b"]
[1] "c" "d"
index<-x>"a"
> index
[1] FALSE TRUE TRUE TRUE FALSE
> x[index]
[1] "b" "c" "d"
> #con matrices
> x<.matrix(1:10, 2, 5)
Error in .matrix(1:10, 2, 5) : could not find function ".matrix"
> x<- matrix(1:10, 2, 5)
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> x[1,]
[1] 1 3 5 7 9
> x[,4]
[1] 7 8
> x[1,3]
[1] 5
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> x<-matrix(1:20, 5, 4)
> x[3,4]
[1] 18
> x[3, 4, drop = FALSE]
[,1]
[1,] 18
> x[1,]
class(x[1,])
[1] "integer"
> x
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
> airquality[1:7,]
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
7 23 299 8.6 65 5 7
no_faltantes<-complete.cases(airquality)
> no_faltantes
[1] TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE FALS
E TRUE TRUE
[14] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRU
E FALSE FALSE
[27] FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALS
E TRUE FALSE
[40] TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE TRUE TRUE TRU
E TRUE FALSE
[53] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRU
E TRUE FALSE
[66] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE TRU
E TRUE TRUE
[79] TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRU
E TRUE TRUE
[92] TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALS
E FALSE TRUE
[105] TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALS
E TRUE TRUE
[118] TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRU
E TRUE TRUE
[131] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRU
E TRUE TRUE
[144] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE
airquality[no_faltantes,][1:5]
Ozone Solar.R Wind Temp Month
1 41 190 7.4 67 5
2 36 118 8.0 72 5
3 12 149
#Función plot
> plot(c(1, 2, 3), c(4, 5, 5))
> plot(c(1, 2, 3), c(4, 5, 5), pch="x")
> plot(c(1, 2, 3), c(4, 5, 5), pch="m")
> plot(c(1, 3), c(1, 8), type = "n", xlab = "Valores de x", ylab = "Va
lores de y")
> #la anterior es una gráfica vacía
> #c(1, 3), c(1, 8) informa sobre el rotulado de los ejes
> #type = "n"Informa que es una gráfica sin puntos
> #xlab = "Valores de x", ylab = "Valores de y" Etiqueta de los ejes
> #Podemos agregar algunos puntos
> x<-c(1, 2, 3)
> y<-c(2, 4, 8)
> points(x, y)
> #Queremos agregar una línea (Ajuste lineal)
> mi_linea<-lm(y~x)
> abline(mi_linea)
> class(mi_linea)
[1] "lm"
> mi_linea

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept) x
-1.333 3.000

> #superponer otra linea


> lines(c(1,4), c(4,7))
> #para diferenciarla podemos cambiarle el color
> lines(c(1,4), c(4,7), col = "green")
> #para guardar la gráfica en R: Export
> #También se puede guardar con las instrucciones pdf("Archivo.pdf") p
ng("Archivo.png")
> #Jpeg("Archivo.jpeg) postscript("Archivo.ps") se debe dar la cadena
de ruta
> #Funciones gráficas de alto nivel
> iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6
hist(iris$Sepal.Length, freq = FALSE)
> hist(iris$Sepal.Length)
> #Se puede agregar freq = FALSE para que en el eje y pinte la probabi
lidad y no la frecuencia

hist(iris$Sepal.Length, breaks = 10, col = "red")


> datos<-iris$Sepal.Width
> h<-hist(datos, breaks = 10, col = "green")
> xfit<-seq(min(datos), max(datos), length = 40)
> yfit<-dnorm(xfit, mean = mean(datos), sd = sd(datos))
> yfit<-yfit*diff(h$mids[1:2])*length(datos)
> lines(xfit, yfit, col = "blue", lwd = 2)
> density(datos)

Call:
density.default(x = datos)

Data: datos (150 obs.); Bandwidth 'bw' = 0.1233

x y
Min. :1.630 Min. :0.0002431
1st Qu.:2.415 1st Qu.:0.0353665
Median :3.200 Median :0.2170174
Mean :3.200 Mean :0.3181879
3rd Qu.:3.985 3rd Qu.:0.5372552
Max. :4.770 Max. :1.0623691
> plot(density(datos))
mtcars
mpg cyl disp hp drat wt qsec vs am gear car
b
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4
4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4
4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4
1
Hornet 4 Drive 21.4
mtcars$mpg
[1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3
15.2 10.4 10.4
[17] 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8
19.7 15.0 21.4
> row.names(mtcars)
[1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710"
[4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant"
[7] "Duster 360" "Merc 240D" "Merc 230"
[10] "Merc 280" "Merc 280C" "Merc 450SE"
[13] "Merc 450SL" "Merc 450SLC" "Cadillac Fleetwood"
[16] "Lincoln Continental" "Chrysler Imperial" "Fiat 128"
[19] "Honda Civic" "Toyota Corolla" "Toyota Corona"
[22] "Dodge Challenger" "AMC Javelin" "Camaro Z28"
[25] "Pontiac Firebird" "Fiat X1-9" "Porsche 914-2"
[28] "Lotus Europa" "Ford Pantera L" "Ferrari Dino"
[31] "Maserati Bora" "Volvo 142E"
> dotchart(mtcars$mpg, labels = row.names(mtcars))
> tail(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.7 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.9 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.5 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.5 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.6 0 1 5 8
Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.6 1 1 4 2
> boxplot(mpg~cyl, data = mtcars)
hist(datos, main = "Histograma de Frecuencias", sub = "Millas por galó
n", xlab = "Límite de clase para los Datos", ylab = "Frecuencia absolu
ta", breaks = 9, col = "blue" )
h<-hist(datos, main = "Histograma de Frecuencias", sub = "Millas por g
alón", xlab = "Límite de clase para los Datos", ylab = "Frecuencia abs
oluta", breaks = 9, col = "blue")
> xfit<-seq(min(datos), max(datos), length = 40)
> yfit<-dnorm(xfit, mean = mean(datos), sd = sd(datos))
yfit<-yfit*diff(h$mids[1:2])*length(datos)
> lines(xfit, yfit, col = "red", lwd = 2)
boxplot(mpg~cyl, data = mtcars, col = 2:4)
pie(c(50, 50, 50), labels = levels(iris$Species))
install.packages("rgl")
x<-sort(rnorm(1000))
> y<-rnorm(1000)
> z<-rnorm(1000) +atan2(x,y)
> open3d()
wgl
1
plot3d(x, y, z, col = rainbow(1000), type = "p")
x<-iris$Sepal.Length
> y<-iris$Petal.Length
> z<-iris$Sepal.Width
plot3d(iris$Sepal.Length, iris$Petal.Length, iris$Sepal.Width, type =
"s", col = rainbow(150))
plot3d(iris$Sepal.Length, iris$Petal.Length, iris$Sepal.Width, type =
"s", col = rainbow(150), main = "Flores", xlab = "Longitus S", ylab =
"Longitud P", zlab = "Grosor S.")
install.packages("ggplot2")
also installing the dependency ‘isoband’

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/isoband_0.2.1.zip'


Content type 'application/zip' length 3304390 bytes (3.2 MB)
downloaded 3.2 MB
trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/ggplot2_3.3.1.zip'
Content type 'application/zip' length 4023199 bytes (3.8 MB)
downloaded 3.8 MB
package ‘isoband’ successfully unpacked and MD5 sums checked
package ‘ggplot2’ successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\mauricio\AppData\Local\Temp\RtmpkbnHsl\downloaded_packages

>
library(ggplot2)
Warning message:
package ‘ggplot2’ was built under R version 3.6.3
> qplot(carat, price, data = diamonds)
qplot(color, data=diamonds)
qplot(color,price/carat, data=diamonds,geom="boxplot")
> qplot(carat,price,data=dchico,alpha=I(1/10))
qplot(color, data=diamonds, geom="density")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy