3.2 Matrices
3.2.1 Crear una matriz
La función matrix()
permite crear la matriz de un vector especificando las dimensiones, por ejemplo:
matrix(data = 1:9, nrow = 3, ncol = 3, byrow = F)
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
En el siguiente vector se presentan los ingresos totales y de lanzamiento de cada película de la saga Harry Potter.
sales_hp <- c(497066400, 426630300, 401608200, 399302200, 377314200,
359788300, 357233500, 328833900, 141823200, 189432500,
142414700, 135197600, 99635700, 92756000, 134119300,
138752100)
sales_mat <- matrix(sales_hp, nrow = 8, byrow = F)
sales_mat
## [,1] [,2]
## [1,] 497066400 141823200
## [2,] 426630300 189432500
## [3,] 401608200 142414700
## [4,] 399302200 135197600
## [5,] 377314200 99635700
## [6,] 359788300 92756000
## [7,] 357233500 134119300
## [8,] 328833900 138752100
La función dim()
regresa la dimensión de la matriz (renglones y columnas).
dim(sales_mat)
## [1] 8 2
La función nrow()
regresa el número de renglones de la matriz y ncol()
el número de columnas.
nrow(sales_mat)
## [1] 8
ncol(sales_mat)
## [1] 2
3.2.2 Nombres de matrices
En R es posible agregar nombres a los renglones y columnas de una matriz con las funciones colnames()
y rownames()
.
Considerando los siete títulos de la saga, asignamos los títulos de las películas a los renglones con la función rownames()
:
titles_hp <- c(
"1. HP and the Sorcerer's Stone",
"8. HP and the Deathly Hallows Part 2",
"4. HP and the Goblet of Fire",
"2. HP and the Chamber of Secrets",
"5. HP and the Order of the Phoenix",
"6. HP and the Half-Blood Prince",
"3. HP and the Prisoner of Azkaban",
"7. HP and the Deathly Hallows Part 1")
rownames(sales_mat) <- titles_hp
sales_mat
## [,1] [,2]
## 1. HP and the Sorcerer's Stone 497066400 141823200
## 8. HP and the Deathly Hallows Part 2 426630300 189432500
## 4. HP and the Goblet of Fire 401608200 142414700
## 2. HP and the Chamber of Secrets 399302200 135197600
## 5. HP and the Order of the Phoenix 377314200 99635700
## 6. HP and the Half-Blood Prince 359788300 92756000
## 3. HP and the Prisoner of Azkaban 357233500 134119300
## 7. HP and the Deathly Hallows Part 1 328833900 138752100
Ej: Tipo de ventas.
Usando la función colnames()
asigna el nombre del tipo de ventas a cada columna:
sales_hp <- c("total", "release_date")
colnames() <-
sales_mat
3.2.3 Selección de elementos en una matriz
Al igual que un vector, los elementos de una matriz pueden seleccionarse con un vector de posiciones o un vector de nombres. Pero, en este se define la posición de ambas dimensiones, renglones y columnas [ , ]
.
Por ejemplo, si queremos obtener una submatriz para las primeras tres películas de las ventas :
sales_mat[c(1, 4, 7), 1:2]
## total release_date
## 1. HP and the Sorcerer's Stone 497066400 141823200
## 2. HP and the Chamber of Secrets 399302200 135197600
## 3. HP and the Prisoner of Azkaban 357233500 134119300
O bien:
titles_first3 <- c("1. HP and the Sorcerer's Stone",
"2. HP and the Chamber of Secrets",
"3. HP and the Prisoner of Azkaban")
sales_mat[titles_first3, ]
## total release_date
## 1. HP and the Sorcerer's Stone 497066400 141823200
## 2. HP and the Chamber of Secrets 399302200 135197600
## 3. HP and the Prisoner of Azkaban 357233500 134119300
3.2.4 Operaciones en matrices
Al igual que los vectores, las operaciones son elemento a elemento o element wise.
Siguiendo con el ejemplo de ingresos, para facilitar la lectura de los datos dividimos entre un millón cada valor.
sales_mat_mill <- sales_mat/1e6
sales_mat_mill
## total release_date
## 1. HP and the Sorcerer's Stone 497.0664 141.8232
## 8. HP and the Deathly Hallows Part 2 426.6303 189.4325
## 4. HP and the Goblet of Fire 401.6082 142.4147
## 2. HP and the Chamber of Secrets 399.3022 135.1976
## 5. HP and the Order of the Phoenix 377.3142 99.6357
## 6. HP and the Half-Blood Prince 359.7883 92.7560
## 3. HP and the Prisoner of Azkaban 357.2335 134.1193
## 7. HP and the Deathly Hallows Part 1 328.8339 138.7521
Lo mismo sucede con un vector. Supongamos que el siguiente vector contiene el número de cines en los que se exhibió cada película.
theaters_vec <- c(3672, 4375, 3858, 3682, 4285, 4325, 3855, 4125)
theaters_vec
## [1] 3672 4375 3858 3682 4285 4325 3855 4125
Calculemos el ingreso promedio por cada cine para el total de ingresos y en la fecha de lanzamiento.
sales_mat_avg <- sales_mat/theaters_vec
sales_mat_avg
## total release_date
## 1. HP and the Sorcerer's Stone 135366.67 38622.88
## 8. HP and the Deathly Hallows Part 2 97515.50 43298.86
## 4. HP and the Goblet of Fire 104097.51 36914.13
## 2. HP and the Chamber of Secrets 108447.09 36718.52
## 5. HP and the Order of the Phoenix 88054.66 23252.21
## 6. HP and the Half-Blood Prince 83188.05 21446.47
## 3. HP and the Prisoner of Azkaban 92667.57 34791.00
## 7. HP and the Deathly Hallows Part 1 79717.31 33636.87
Ej: Total de visitas
Calcula el número de visitas si el costo del boleto promedio es de $8.89 dólares.
visits_mat <- sales_mat
visits_mat
3.2.5 Operaciones por dimensiones
En R existen funciones que permiten realizar operaciones por columnas o renglones de una matriz.
colSums()
colSums(sales_mat_mill)
## total release_date
## 3147.777 1074.131
rowSums()
rowSums(sales_mat_mill)
## 1. HP and the Sorcerer's Stone 8. HP and the Deathly Hallows Part 2
## 638.8896 616.0628
## 4. HP and the Goblet of Fire 2. HP and the Chamber of Secrets
## 544.0229 534.4998
## 5. HP and the Order of the Phoenix 6. HP and the Half-Blood Prince
## 476.9499 452.5443
## 3. HP and the Prisoner of Azkaban 7. HP and the Deathly Hallows Part 1
## 491.3528 467.5860
Ej: Ingresos promedio
Usando la función colMeans()
calcula el ingreso promedio total y en la fecha de lanzamiento.
avg_income <- colMeans()
3.2.6 Nuevos valores
Existen funciones que nos permiten aumentar la dimensión de una matriz. Para columnas cbind()
y reglones rbind()
.
Agreguemos el vector de número de salas a la matriz de ingresos por millón.
sales_mat_theat <- cbind(sales_mat_mill, theaters_vec)
sales_mat_theat
## total release_date theaters_vec
## 1. HP and the Sorcerer's Stone 497.0664 141.8232 3672
## 8. HP and the Deathly Hallows Part 2 426.6303 189.4325 4375
## 4. HP and the Goblet of Fire 401.6082 142.4147 3858
## 2. HP and the Chamber of Secrets 399.3022 135.1976 3682
## 5. HP and the Order of the Phoenix 377.3142 99.6357 4285
## 6. HP and the Half-Blood Prince 359.7883 92.7560 4325
## 3. HP and the Prisoner of Azkaban 357.2335 134.1193 3855
## 7. HP and the Deathly Hallows Part 1 328.8339 138.7521 4125
Ej: Más información
Agrega un reglón a la matriz sales_mat_theat
con el promedio de ventas totales, ingresos en la fechas de lanzamientos y salas de exhibición.
Tip: Usa las funciones colMeans()
y rbind()
.
avg_row <- colMeans()
rbind(sales_mat_theat, )