Java教程

R语言矩阵(使用r语言求解矩阵),数组

本文主要是介绍R语言矩阵(使用r语言求解矩阵),数组,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
> a <- c(1:20)给a赋值
> sum(a)求和
[1] 210
> max(a)最大值
[1] 20
> min(a)最小值
[1] 1
> mean(a)平均值
[1] 10.5
> var(a)方差
[1] 35
> sd(a)标准差
[1] 5.91608
> prod(a)连乘
[1] 2.432902e+18
> median(a)中位数
[1] 10.5
> quantile(a,0.4)40%数
40% 
8.6 
> a
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

  

> vec <- rep("one",20)  新建重复向量vec
> names(a) <- vec   将vec作为向量a的索引名
> a
one one one one one one one one one one one one one one one one one one one one 
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
> which.max(a) 返回的是最大值的索引
one 
 20 

  

> b <- matrix(a,4,5)
> b
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20
> c <- matrix(a,4,5,byrow = T)
> c
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    6    7    8    9   10
[3,]   11   12   13   14   15

矩阵设立
> c[1,1] <- 582
> c
     [,1] [,2] [,3] [,4] [,5]
[1,]  582    2    3    4    5
[2,]    6    7    8    9   10
[3,]   11   12   13   14   15
[4,]   16   17   18   19   20

矩阵修改

> a1 <- c("a1","a2","a3","a4","a5")
> b1 <- c("b1","b2","b3","b4")
> dimnames(c) <- list(b1,a1)
> c
    a1 a2 a3 a4 a5
b1 582  2  3  4  5
b2   6  7  8  9 10
b3  11 12 13 14 15
b4  16 17 18 19 20
给矩阵赋值索引名

  

> t(c)
    b1 b2 b3 b4
a1 582  6 11 16
a2   2  7 12 17
a3   3  8 13 18
a4   4  9 14 19
a5   5 10 15 20

转换

> b %*% c
     [,1] [,2]
[1,]   67   94
[2,]   88  124
> b
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> c
     [,1] [,2]
[1,]    6    9
[2,]    7   10
[3,]    8   11

矩阵的外积

> t(b)*c
     [,1] [,2]
[1,]    6   18
[2,]   21   40
[3,]   40   66

矩阵的内积

  

> f <- diag(c(5,6,7,8)) 生成对角矩阵
> f
     [,1] [,2] [,3] [,4]
[1,]    5    0    0    0
[2,]    0    6    0    0
[3,]    0    0    7    0
[4,]    0    0    0    8
> det(f)  求行列式
[1] 1680
> solve(f) 求逆矩阵
     [,1]      [,2]      [,3]  [,4]
[1,]  0.2 0.0000000 0.0000000 0.000
[2,]  0.0 0.1666667 0.0000000 0.000
[3,]  0.0 0.0000000 0.1428571 0.000
[4,]  0.0 0.0000000 0.0000000 0.125
> eigen(f) 求解矩阵
eigen() decomposition
$values
[1] 8 7 6 5

$vectors
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    1    0
[3,]    0    1    0    0
[4,]    1    0    0    0

  

这篇关于R语言矩阵(使用r语言求解矩阵),数组的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!