R语言矩阵基础操作
#1.用C()函数生成向量
dat_vec <- c(1:1:20)
dat_vec
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
[18] 18 19 20
#2.用:运算符生成向量
1:20
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#3.用seq()函数生成向量
seq(from=1,to=20,by=1)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
dat_vec <- seq(from=1,to=20,by=1);dat_vec
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#用matrix()函数转换成矩阵
matrix(dat_vec,ncol = 5)
[,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
#给矩阵的行列命名
colnames(dat_mat) <- c(“vec1”,“vec2”,“vec3”,“vec4”,“vec5”)
dat_mat
vec1 vec2 vec3 vec4 vec5
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
#筛选矩阵元素
z <- dat_mat[dat_mat > 10]
z
[1] 11 12 13 14 15 16 17 18 19 20
#在原基础上+2.5
y <- matrix(c(0,0,0,0,0,0,0,0,0,0,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5),nrow = 4,ncol = 5);y
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0.0 2.5 2.5
[2,] 0 0 0.0 2.5 2.5
[3,] 0 0 2.5 2.5 2.5
[4,] 0 0 2.5 2.5 2.5
w <- dat_mat + y;w
vec1 vec2 vec3 vec4 vec5
[1,] 1 5 9.0 15.5 19.5
[2,] 2 6 10.0 16.5 20.5
[3,] 3 7 13.5 17.5 21.5
[4,] 4 8 14.5 18.5 22.5
#分别对行列求平均值
apply(w,1,mean)
[1] 10.0 11.0 12.5 13.5
apply(w,2,mean)
vec1 vec2 vec3 vec4 vec5
2.50 6.50 11.75 17.00 21.00
rowMeans(w)
[1] 10.0 11.0 12.5 13.5
colMeans(w)
vec1 vec2 vec3 vec4 vec5
2.50 6.50 11.75 17.00 21.00