R语言学习(2)-向量矩阵和数组
【摘要】 向量矩阵和数组
1.vector函数可以创建指定类型、长度的矢量
(其结果中的值可以是0,FLASE,空字符串)
>&nbs...
向量矩阵和数组
1.vector函数可以创建指定类型、长度的矢量
(其结果中的值可以是0,FLASE,空字符串)
> vector("numeri c",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")))), , eightfive six sevenone 1 5 9two 2 6 10three 3 7 11four 4 8 12, , ninefive six sevenone 13 17 21two 14 18 22three 15 19 23four 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 threeone 1 5 9two 2 6 10three 3 7 11four 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 threeone 1 2 3two 4 5 6three 7 8 9four 10 11 12
7.行名 rownames
列名 colnames
维度名 dimnames
8.索引数组
> a_matrix[1,c("two","three")]two three2 3> a_matrix[1, ]one two three1 2 3> a_matrix[ ,c("one","three")]one threeone 1 3two 4 6three 7 9four 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 threeone 2 10 18two 4 12 20three 6 14 22four 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 threeone 1 2 3 2 10 18two 4 5 6 4 12 20three 7 8 9 6 14 22four 10 11 12 8 16 24> rbind(a_matrix, another_matrix)one two threeone 1 2 3two 4 5 6three 7 8 9four 10 11 12one 2 10 18two 4 12 20three 6 14 22four 8 16 24
10.数组算数
矩阵内乘:
> a_matrix %*% t(a_matrix)one two three fourone 14 32 50 68two 32 77 122 167three 50 122 194 266four 68 167 266 365
矩阵外乘:
> 1:3 %o% 4:6[,1] [,2] [,3][1,] 4 5 6[2,] 8 10 12[3,] 12 15 18
文章来源: blog.csdn.net,作者:冰水比水冰,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/luoyhang003/article/details/38338565
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)