向量矩阵和数组
1.vector函数可以创建指定类型、长度的矢量
(其结果中的值可以是0,FLASE,空字符串)
> vector("numeric",5)
[1] 0 0 0 0 0
> vector("complex",6)
[1] 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i
> vector("logical",6)
[1] FALSE FALSE FALSE FALSE FALSE FALSE
> vector("character",4)
[1] "" "" "" ""
> vector("list",5)
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
使用每个类型的包装函数创建矢量与vector等价
> numeric(5)
[1] 0 0 0 0 0
> complex(5)
[1] 0+0i 0+0i 0+0i 0+0i 0+0i
2.序列
使用seq.int函数创建序列
> seq.int(5,8) #相当于 5:8
[1] 5 6 7 8
> seq.int(3,12,2)
#可指定步长为2[1] 3 5 7 9 11
seq_len函数创建一个从1到它的输入值的序列
> seq_len(5)
[1] 1 2 3 4 5
3.长度
length函数查向量长度
> length(4:9)
[1] 6
nchar函数查字符串长度
> str <- c("Peter","Kate","Jim")
> length(str)
[1] 3
> nchar(str)
[1] 5 4 3
4.索引
> x <- (1:5)^2
> x[c(1,3,5)]
[1] 1 9 25
> x[c(-2,-4)]
[1] 1 9 25
> x[c(TRUE,FALSE,TRUE,FALSE,TRUE)]
[1] 1 9 25
5.数组
使用array函数创建数组,为他们传入两个向量(值和维度)作为参数
> (three_d_array <- array(1:24,dim = c(4,3,2),dimnames = list(c("one","two","three","four"),c("five","six","seven"),c("eight","nine"))))
, , eight
five six seven
one 1 5 9
two 2 6 10
three 3 7 11
four 4 8 12
, , nine
five six seven
one 13 17 21
two 14 18 22
three 15 19 23
four 16 20 24
6.矩阵
创建矩阵使用matrix函数只需要指定行数和列数
> (a_matrix <- matrix(1:12,nrow = 4,dimnames = list(c("one","two","three","four"),c("one","two","three"))))
one two three
one 1 5 9
two 2 6 10
three 3 7 11
four 4 8 12
创建矩阵时传入的值默认会按列填充,可指定参数byrow = TRUE来按行填充
> (a_matrix <- matrix(1:12,nrow = 4,byrow = TRUE,dimnames = list(c("one","two","three","four"),c("one","two","three"))))
one two three
one 1 2 3
two 4 5 6
three 7 8 9
four 10 11 12
7.行名 rownames
列名 colnames
维度名 dimnames
8.索引数组
> a_matrix[1,c("two","three")]
two three
2 3
> a_matrix[1, ]
one two three
1 2 3
> a_matrix[ ,c("one","three")]
one three
one 1 3
two 4 6
three 7 9
four 10 12
9.合并矩阵
c函数可以把矩阵转化成向量然后合并
> (another_matrix <- matrix(seq.int(2,24,2),nrow = 4,dimnames = list(c("one","two","three","four"),c("one","two","three"))))
one two three
one 2 10 18
two 4 12 20
three 6 14 22
four 8 16 24
> c(a_matrix,another_matrix)
[1] 1 4 7 10 2 5 8 11 3 6 9 12 2 4 6 8 10 12 14 16 18 20 22 24
使用cbind、rbind函数可以按行、列绑定矩阵
> cbind(a_matrix, another_matrix)
one two three one two three
one 1 2 3 2 10 18
two 4 5 6 4 12 20
three 7 8 9 6 14 22
four 10 11 12 8 16 24
> rbind(a_matrix, another_matrix)
one two three
one 1 2 3
two 4 5 6
three 7 8 9
four 10 11 12
one 2 10 18
two 4 12 20
three 6 14 22
four 8 16 24
10.数组算数
矩阵内乘:
> a_matrix %*% t(a_matrix)
one two three four
one 14 32 50 68
two 32 77 122 167
three 50 122 194 266
four 68 167 266 365
矩阵外乘:
> 1:3 %o% 4:6
[,1] [,2] [,3]
[1,] 4 5 6
[2,] 8 10 12
[3,] 12 15 18
R语言学习(2)