logo

R – Matrices

matriz R Es una disposición bidimensional de datos en filas y columnas.

En una matriz, las filas son las que corren horizontalmente y las columnas son las que corren verticalmente. En programación R , las matrices son estructuras de datos homogéneas y bidimensionales. Estos son algunos ejemplos de matrices:



R - MatricesGeeksforgeeks

R – Matrices

Creando una matriz en R

Para crear una matriz en R necesitas usar la función llamada matriz() .

Los argumentos a este matriz() son el conjunto de elementos del vector. Tienes que pasar cuántos números de filas y cuántos números de columnas quieres tener en tu matriz.



Nota: De forma predeterminada, las matrices están en orden de columnas.

Sintaxis para crear R-Matrix

matriz (datos, nrow, ncol, byrow, dimnames)

Parámetros:



  • datos - valores que desea ingresar
  • ahora – No. de filas
  • ncol – No. de columnas
  • byrow – pista lógica, si el valor 'verdadero' se asignará por filas
  • dimnames – nombres de filas y columnas

Ejemplo:

clasificación de selección java

R




# R program to create a matrix> > A =>matrix>(> > ># Taking sequence of elements> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> > ># No of rows> >nrow = 3,> > ># No of columns> >ncol = 3,> > ># By default matrices are in column-wise order> ># So this parameter decides how to arrange the matrix> >byrow =>TRUE> )> > # Naming rows> rownames>(A) =>c>(>'a'>,>'b'>,>'c'>)> > # Naming columns> colnames>(A) =>c>(>'c'>,>'d'>,>'e'>)> > cat>(>'The 3x3 matrix: '>)> print>(A)>

>

>

Producción

The 3x3 matrix: c d e a 1 2 3 b 4 5 6 c 7 8 9>

Creando matrices especiales en R

R permite la creación de varios tipos diferentes de matrices con el uso de argumentos pasados ​​a la función Matrix().

1. Matriz donde todas las filas y columnas se llenan con una única constante 'k':

Para crear una matriz R de este tipo, la sintaxis se proporciona a continuación:

Sintaxis: matriz(k, m, n)

Parámetros:
k: el constante
metro: número de filas
norte: número de columnas

Ejemplo:

R




# R program to illustrate> # special matrices> # Matrix having 3 rows and 3 columns> # filled by a single constant 5> print>(>matrix>(5, 3, 3))>

>

>

Producción

 [,1] [,2] [,3] [1,] 5 5 5 [2,] 5 5 5 [3,] 5 5 5>

2. Matriz diagonal:

Una matriz diagonal es una matriz en la que las entradas fuera de la diagonal principal son todas cero. Para crear una matriz R de este tipo, la sintaxis se proporciona a continuación:

Sintaxis: diag(k, m, n)
Parámetros:
k: las constantes/matriz
metro: número de filas
norte: número de columnas

Ejemplo:

R




# R program to illustrate> # special matrices> # Diagonal matrix having 3 rows and 3 columns> # filled by array of elements (5, 3, 3)> print>(>diag>(>c>(5, 3, 3), 3, 3))>

>

>

Producción

 [,1] [,2] [,3] [1,] 5 0 0 [2,] 0 3 0 [3,] 0 0 3>

3. Matriz de identidad:

Una matriz identidad en la que todos los elementos de la diagonal principal son unos y todos los demás elementos son ceros. Para crear una matriz R de este tipo, la sintaxis se proporciona a continuación:

Sintaxis: diag(k, m, n)
Parámetros:
k: 1
metro: número de filas
norte: número de columnas

objeto json de cadena

Ejemplo:

R




# R program to illustrate> # special matrices> # Identity matrix having> # 3 rows and 3 columns> print>(>diag>(1, 3, 3))>

>

>

Producción

 [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1>

4. Métricas de matriz

Las métricas de Matrix le informan sobre la Matrix que creó. Es posible que desee saber el número de filas, el número de columnas y las dimensiones de una matriz.

El siguiente ejemplo le ayudará a responder las siguientes preguntas:

  • ¿Cómo se puede saber la dimensión de la matriz?
  • ¿Cómo puedes saber cuántas filas hay en la matriz?
  • ¿Cuántas columnas hay en la matriz?
  • ¿Cuantos elementos hay en la matriz?

Ejemplo:

R




# R program to illustrate> # matrix metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> cat>(>'Dimension of the matrix: '>)> print>(>dim>(A))> cat>(>'Number of rows: '>)> print>(>nrow>(A))> cat>(>'Number of columns: '>)> print>(>ncol>(A))> cat>(>'Number of elements: '>)> print>(>length>(A))> # OR> print>(>prod>(>dim>(A)))>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 Dimension of the matrix: [1] 3 3 Number of rows: [1] 3 Number of columns: [1] 3 Number of elements: [1] ...>

Accediendo a elementos de una matriz R

Podemos acceder a elementos en las matrices R usando la misma convención que se sigue en los marcos de datos. Entonces, tendrá una matriz seguida de un corchete con una coma entre la matriz.

El valor antes de la coma se usa para acceder a las filas y el valor que está después de la coma se usa para acceder a las columnas. Ilustremos esto tomando un código R simple.

Accediendo a filas:

R




# R program to illustrate> # access rows in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Accessing first and second row> cat>(>'Accessing first and second row '>)> print>(A[1:2, ])>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 Accessing first and second row [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6>

Accediendo a columnas:

R




# R program to illustrate> # access columns in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Accessing first and second column> cat>(>'Accessing first and second column '>)> print>(A[, 1:2])>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 Accessing first and second column [,1] [,2] [1,] 1 2 [2,] 4 5 [3,] 7 8>

Más ejemplos de acceso a elementos de una matriz R:

R




# R program to illustrate> # access an entry in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Accessing 2> print>(A[1, 2])> # Accessing 6> print>(A[2, 3])>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 [1] 2 [1] 6>

Accediendo a submatrices en R:

Podemos acceder a la submatriz en una matriz usando el colon(:) operador.

R




¿Qué es el sistema de archivos de Linux?
# R program to illustrate> # access submatrices in a matrix> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> cat>(>'Accessing the first three rows and the first two columns '>)> print>(A[1:3, 1:2])>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 Accessing the first three rows and the first two columns [,1] [,2] [1,] 1 2 [2,] 4 5 [3...>

Modificación de elementos de una matriz R

En R puedes modificar los elementos de las matrices mediante una asignación directa.

Ejemplo:

R




# R program to illustrate> # editing elements in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Editing the 3rd rows and 3rd column element> # from 9 to 30> # by direct assignments> A[3, 3] = 30> cat>(>'After edited the matrix '>)> print>(A)>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 After edited the matrix [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 30>

Concatenación de matriz R

La concatenación de matrices se refiere a la combinación de filas o columnas de una matriz R existente.

Concatenación de una fila:

La concatenación de una fila a una matriz se realiza usando enlazar() .

R




# R program to illustrate> # concatenation of a row in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Creating another 1x3 matrix> B =>matrix>(> >c>(10, 11, 12),> >nrow = 1,> >ncol = 3> )> cat>(>'The 1x3 matrix: '>)> print>(B)> # Add a new row using rbind()> C =>rbind>(A, B)> cat>(>'After concatenation of a row: '>)> print>(C)>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 The 1x3 matrix: [,1] [,2] [,3] [1,] 10 11 12 After concatenation of a row: [,1] [,2] [,3...>

Concatenación de una columna:

La concatenación de una columna a una matriz se realiza mediante vincular() .

R




# R program to illustrate> # concatenation of a column in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Creating another 3x1 matrix> B =>matrix>(> >c>(10, 11, 12),> >nrow = 3,> >ncol = 1,> >byrow =>TRUE> )> cat>(>'The 3x1 matrix: '>)> print>(B)> # Add a new column using cbind()> C =>cbind>(A, B)> cat>(>'After concatenation of a column: '>)> print>(C)>

>

>

Producción

The 3x3 matrix: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 The 3x1 matrix: [,1] [1,] 10 [2,] 11 [3,] 12 After concatenation of a column: [,1] [,2] ...>

Inconsistencia de dimensiones: Tenga en cuenta que debe asegurarse de la coherencia de las dimensiones entre la matriz antes de realizar esta concatenación de matrices.

R


java si declaración



# R program to illustrate> # Dimension inconsistency in metrics concatenation> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'The 3x3 matrix: '>)> print>(A)> # Creating another 1x3 matrix> B =>matrix>(> >c>(10, 11, 12),> >nrow = 1,> >ncol = 3,> )> cat>(>'The 1x3 matrix: '>)> print>(B)> # This will give an error> # because of dimension inconsistency> C =>cbind>(A, B)> cat>(>'After concatenation of a column: '>)> print>(C)>

>

>

Producción:

The 3x3 matrix:  [, 1] [, 2] [, 3] [1, ] 1 2 3 [2, ] 4 5 6 [3, ] 7 8 9 The 1x3 matrix:  [, 1] [, 2] [, 3] [1, ] 10 11 12 Error in cbind(A, B) : number of rows of matrices must match (see arg 2)>

Agregar filas y columnas en una matriz R

Para agregar una fila en R-matrix puedes usar enlazar() función y para agregar una columna a R-matrix puede usar vincular () función.

Agregar fila

Veamos el siguiente ejemplo sobre cómo agregar una fila en R-matrix.

Ejemplo:

R




# Create a 3x3 matrix> number <->matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'Before inserting a new row: '>)> print>(number)> # New row to be inserted> new_row <->c>(10, 11, 12)># Define the new row> # Inserting the new row at the second position> A <->rbind>(number[1, ], new_row, number[-1, ])> cat>(>' After inserting a new row: '>)> print>(number)>

>

>

Producción

Before inserting a new row: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 After inserting a new row: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,]...>

Agregar columna

Veamos el siguiente ejemplo sobre cómo agregar columnas en R-matrix.

R




# Create a 3x3 matrix> number <->matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'Before adding a new column: '>)> print>(number)> # New column to be added> new_column <->c>(10, 11, 12)># Define the new column> # Adding the new column at the end> number <->cbind>(number, new_column)> cat>(>' After adding a new column: '>)> print>(number)>

>

>

Producción

Before adding a new column: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 After adding a new column: new_column [1,] 1 2 3 10 [2,] 4 5 6 1...>

Eliminar filas y columnas de una matriz R

Para eliminar una fila o columna, primero que nada, debe acceder a esa fila o columna y luego insertar un signo negativo antes de esa fila o columna. Indica que tuviste que eliminar esa fila o columna.

Eliminación de fila:

R




verificación nula de java

# R program to illustrate> # row deletion in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'Before deleting the 2nd row '>)> print>(A)> # 2nd-row deletion> A = A[-2, ]> cat>(>'After deleted the 2nd row '>)> print>(A)>

>

>

Producción

Before deleting the 2nd row [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 After deleted the 2nd row [,1] [,2] [,3] [1,] 1 2 3 [2,] 7 8 9>

Eliminación de columnas:

R




# R program to illustrate> # column deletion in metrics> # Create a 3x3 matrix> A =>matrix>(> >c>(1, 2, 3, 4, 5, 6, 7, 8, 9),> >nrow = 3,> >ncol = 3,> >byrow =>TRUE> )> cat>(>'Before deleting the 2nd column '>)> print>(A)> # 2nd-row deletion> A = A[, -2]> cat>(>'After deleted the 2nd column '>)> print>(A)>

>

>

Producción

Before deleting the 2nd column [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 After deleted the 2nd column [,1] [,2] [1,] 1 3 [2,] 4 6 [3,] 7 9>

Hemos hablado sobre las matrices R y sus operaciones básicas, como agregar nuevas filas y columnas, eliminar filas y columnas, fusionar matrices, etc.

Espero que esto te haya ayudado a comprender las matrices en R y que ahora puedas usar cómodamente las matrices R en tus proyectos.

Verifique también: