向量定义:x1 = c(1,2,3); x2 = c(1:100)
类型显示:mode(x1)
向量长度:length(x2)
向量元素显示:x1[c(1,2,3)]
多维向量:multi-dimensional vector:rbind(x1,x2); cbind(x1,x2)
1 > x = c(1,2,3,4,5,6) 2 > y = c(6,5,4,3,2,1) 3 > z = rbind(x,y) 4 > z 5 [,1] [,2] [,3] [,4] [,5] [,6] 6 x 1 2 3 4 5 6 7 y 6 5 4 3 2 1 8 > z = cbind(x,y) 9 > z 10 x y 11 [1,] 1 6 12 [2,] 2 5 13 [3,] 3 4 14 [4,] 4 3 15 [5,] 5 2 16 [6,] 6 1 17 >
一维变二维向量:
> mtx=matrix(1:12, nrow=3, ncol=4) > mtx [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12 > mtx=matrix(1:12, nrow=3, ncol=4, byrow=T) > mtx [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 5 6 7 8 [3,] 9 10 11 12
矩阵转置:
> mtx [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 5 6 7 8 [3,] 9 10 11 12 > t(mtx) [,1] [,2] [,3] [1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12
矩阵相乘:
> a = mtx%*%t(mtx)> a [,1] [,2] [,3] [1,] 30 70 110 [2,] 70 174 278 [3,] 110 278 446
对角线矩阵:
> diag(a) [1] 30 174 446 > diag(diag(a)) [,1] [,2] [,3] [1,] 30 0 0 [2,] 0 174 0 [3,] 0 0 446 > diag(3) [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1
逆矩阵:
> a = matrix(rnorm(16),4,4) > a [,1] [,2] [,3] [,4] [1,] 0.5116868 -0.5839355 0.9038526 -1.5063944 [2,] -1.0657446 -2.2067686 1.2187536 0.1999609 [3,] 0.4784326 -2.1762163 0.1937103 0.0255462 [4,] -2.5393649 -0.1884904 2.7594314 -0.6955184 > solve(a) [,1] [,2] [,3] [,4] [1,] -1.7427160 -5.204571 5.530340 2.4812951 [2,] -0.6103805 -1.743684 1.396904 0.8719984 [3,] -2.2412701 -6.107496 6.505573 3.3373229 [4,] -2.3639756 -4.756515 5.240446 2.5072471 > solve(a)%*%a [,1] [,2] [,3] [,4] [1,] 1.000000e+00 2.390341e-15 -1.167469e-15 1.311885e-16 [2,] 5.746272e-17 1.000000e+00 -2.270319e-16 1.114018e-16 [3,] -2.550044e-16 -1.047339e-16 1.000000e+00 -1.275022e-16 [4,] 5.872039e-16 -1.514197e-15 -7.502679e-17 1.000000e+00
Data Exploration
平均值:mean(x1)
求和:sum(x1)
最大值:max(x1)
最小值:min(x1)
方差:var(x1)
标准差:sd(x1)
累乘:prod(x1)
公差向量
> seq(5, 10, by=2) [1] 5 7 9 > seq(5, 50, length=13) [1] 5.00 8.75 12.50 16.25 20.00 23.75 27.50 31.25 35.00 38.75 42.50 46.25 [13] 50.00
字母向量
> letters [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" [19] "s" "t" "u" "v" "w" "x" "y" "z" > letters[1:4] [1] "a" "b" "c" "d" > letters[1:30] [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" [19] "s" "t" "u" "v" "w" "x" "y" "z" NA NA NA NA
下标函数:which()
> a=c(2,3,4,5,6,7,2,3,4,8,9,5) > which.max(a) [1] 11 > which(a==2) [1] 1 7 > which(a>3) [1] 3 4 5 6 9 10 11 12 > a[which(a>3)] [1] 4 5 6 7 4 8 9 5
向量排序:rev(x), sort(x)
线性方程组:Linear Equations
时间: 2024-10-14 19:43:09