Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 70
Warning – R consistently works element by element
ОглавлениеNote that while exp(A), for example, is well defined for a matrix as the sum of the series:
R will resort to calculating the exp() element by element!
Using the same matrix A as in the aforementioned code:
# This is the matrix A: A ## [,1] [,2] [,3] ## [1,] 0 1 2 ## [2,] 3 4 5 ## [3,] 6 7 8 # The exponential of A: exp(A) ## [,1] [,2] [,3] ## [1,] 1.00000 2.718282 7.389056 ## [2,] 20.08554 54.598150 148.413159 ## [3,] 403.42879 1096.633158 2980.957987
The same holds for all other functions of base R:
# The natural logarithm log(A) ## [,1] [,2] [,3] ## [1,] -Inf 0.000000 0.6931472 ## [2,] 1.098612 1.386294 1.6094379 ## [3,] 1.791759 1.945910 2.0794415 sin(A) ## [,1] [,2] [,3] ## [1,] 0.0000000 0.8414710 0.9092974 ## [2,] 0.1411200 -0.7568025 -0.9589243 ## [3,] -0.2794155 0.6569866 0.9893582
Note also that some operations will collapse the matrix to another (simpler) data type.
# Collapse to a vectore: colSums(A) ## [1] 9 12 15 rowSums(A) ## [1] 3 12 21 # Some functions aggregate the whole matrix to one scalar: mean(A) ## [1] 4 min(A) ## [1] 0
We already saw the function t()
to transpose a matrix. There are a few others available in base R. For example, the function diag()
diagonal matrix that is a subset of the matrix, det()
caluclates the determinant, etc. The function solve()
will solve the equation A %.% x = b
, but when A is missing, it will assume the idenity vector and return the inverse of A.
diag()
solve()
M <- matrix(c(1,1,4,1,2,3,3,2,1), 3, 3) M ## [,1] [,2] [,3] ## [1,] 1 1 3 ## [2,] 1 2 2 ## [3,] 4 3 1 # The diagonal of M: diag(M) ## [1] 1 2 1 # Inverse: solve(M) ## [,1] [,2] [,3] ## [1,] 0.3333333 -0.66666667 0.33333333 ## [2,] -0.5833333 0.91666667 -0.08333333 ## [3,] 0.4166667 -0.08333333 -0.08333333 # Determinant: det(M) ## [1] -12 # The QR composition: QR_M <- qr(M) QR_M$rank ## [1] 3 # Number of rows and columns: nrow(M) ## [1] 3 ncol(M) ## [1] 3 # Sums of rows and columns: colSums(M) ## [1] 6 6 6 srowSums(M) ## [1] 5 5 8 # Means of rows, columns, and matrix: colMeans(M) ## [1] 2 2 2 rowMeans(M) ## [1] 1.666667 1.666667 2.666667 mean(M) ## [1] 2 # Horizontal and vertical concatenation: rbind(M, M) ## [,1] [,2] [,3] ## [1,] 1 1 3 ## [2,] 1 2 2 ## [3,] 4 3 1 ## [4,] 1 1 3 ## [5,] 1 2 2 ## [6,] 4 3 1 cbind(M, M) ## [,1] [,2] [,3] [,4] [,5] [,6] ## [1,] 1 1 3 1 1 3 ## [2,] 1 2 2 1 2 2 ## [3,] 4 3 1 4 3 1