> x <- matrix(rep(1:9),3,3)
> x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

colSums() function computes the sums of matrix columns.

> colSums(x)
[1]  6 15 24

 

diag() function extracts or replaces the diagonal of a matrix, or constructs a diagonal matrix.

> diag(10,3,4)
     [,1] [,2] [,3] [,4]
[1,]   10    0    0    0
[2,]    0   10    0    0
[3,]    0    0   10    0

 

> diag(3)
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

 

 

> diag(5)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    0    1    0    0    0
[3,]    0    0    1    0    0
[4,]    0    0    0    1    0
[5,]    0    0    0    0    1

 

> d
  X1 X2 X3
1  1  3  5
2  2  4  6

 

> colnames(d)
[1] "X1" "X2" "X3"

 

ncol() function returns the number of columns of a matrix.

nrow() function returns the number of rows of a matrix.

> ncol(d)

[1] 3
> nrow(d)
[1] 2

colSums() function computes the sums of matrix columns.
 

> colSums(d)
X1 X2 X3 
 3  7 11 

colMeans() function computes the means of columns of matrix.

> colMeans(d)
 X1  X2  X3 
1.5 3.5 5.5 


det() function calculates the determinant of a matrix

> x <- matrix(c(-2,2,-3,-1,1,3,2,0,-1),3,3)
> x
     [,1] [,2] [,3]
[1,]   -2   -1    2
[2,]    2    1    0
[3,]   -3    3   -1

 

> det(x)
[1] 18

 

t() function transposes a matrix or data.frame.

> d
  X1 X2 X3
1  1  3  5
2  2  4  6

 

t(d)
   [,1] [,2]
X1    1    2
X2    3    4
X3    5    6

 

prod() function returns the multiplication results of all the values present in its arguments.
 

prod(..., na.rm=FALSE)


...: numeric or complex or logical vectors
na.rm: whether missing values be removed or not
...
 

> prod(4:6) #4 × 5 × 6
[1] 120

 

> x <- c(3.2,5,4.3)
> prod(x)  #3.2 × 5 × 4.3
[1] 68.8
Retour à l'accueil