《R语言编程艺术》书上代码实现---第三章矩阵和数组

第三章矩阵和数组

3.1创建矩阵

y=matrix(c(1,2,3,4),nrow=2,ncol=2) #R是按列储存的
y
y[,2]

#创建矩阵每个赋值
m=matrix(nrow = 2,ncol = 2)
m[1,1]=1
m[1,2]=3
m[2,1]=2
m[2,2]=4
m

matrix(c(1,2,3,4,5,6),nrow=2,byrow = T) #改成按行排列byrow

3.2一般矩阵运算

#3.2.1线性代数运算
y%*%y #矩阵乘法
3*y
y+y

#3.2.2矩阵索引
z=matrix(c(1,2,3,4,1,1,0,0,1,0,1,0),nrow=4)
z[,2:3]
z[2:3,] #提取行
z[2:3,2]

y=matrix(c(1,2,3,4,5,6),nrow = 3)
y
y[c(1,3),]=matrix(c(1,1,8,12),nrow = 2)
y

x=matrix(ncol=3,nrow=3)
y=matrix(c(4,5,2,3),nrow=2)
y
x[2:3,2:3]<-y #矩阵赋值
x
y
y[-2,]#取出第二行外的元素

#3.2.3扩展案例:图像操作
library(pixmap)
mtrush1=read.pnm("mtrush1.pgm")
mtrush1
plot(mtrush1)
str(mtrush1)
#pixmap属于S4类型
mtrush1@grey[28,88] #0.0表示黑色,1.0表示白色 中间值为灰色

#将罗斯福总统脸去掉
mtrush2=mtrush1
mtrush2@grey[84:163,135:177]=1
plot(mtrush2)

#将罗斯福总统脸某糊掉
# adds random noise to img, at the range rows,cols of img; img and the
# return value are both objects of class pixmap; the parameter q
# controls the weight of the noise, with the result being 1-q times the
# original image plus q times the random noise
blurpart <- function(img,rows,cols,q) {
  lrows <- length(rows)
  lcols <- length(cols)
  newimg <- img
  randomnoise <- matrix(nrow=lrows, ncol=lcols,runif(lrows*lcols))
  newimg@grey[rows, cols] <- (1-q) * img@grey[rows, cols] + q * randomnoise
  return(newimg)
}

mtrush3=blurpart(mtrush1,84:163,135:177,0.65)
plot(mtrush3)

#3.2.4矩阵元素筛选
x=matrix(c(1,2,3,4,1,1,0,0,1,0,1,0),ncol=2)
x
x[x[,2]>=1,]
j=x[,2]>=1
j
x[j,]

x=matrix(c(1,2,3,4,5,6),ncol=2)
z=c(5,12,13)
x[z%%2==1,]
x[x[,1]>1 & x[,2]>5,] #元素正确但是数据类型不对
x

#3.2.5扩展案例:生成协方差矩阵
makecov <- function(rho,n) {
   m <- matrix(nrow=n,ncol=n)
   m <- ifelse(row(m) == col(m),1,rho) #==是一个函数
   return(m)
}
row(x)
makecov(0.2,3)

3.3对矩阵的行和列调用函数

#3.3.1使用apply()函数
#apply()函数系列 apply() tapply() lapply()
#apply(矩阵,维度编号,应用在行或列的函数,f的可选集)
#维度编号 取1对行应用函数 取2对列应用函数
x
colMeans(x)
apply(x,2,mean)

f=function(x) x/c(2,8)
apply(x,1,f)
t(apply(x,1,f))

#生成0,1的矩阵
copymaj=function(rw,d){
  maj=sum(rw[1:d])/d
  return(if(maj>0.5) 1 else 0)
}
x=matrix(c(1,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0),ncol=4)
x
apply(x,1,copymaj,3)

#3.3.2扩展案例:寻找异常值
findols<-function(x){
  findol<-function(xrow){
    mdn<-median(xrow)
    devs<-abs(xrow-mdn)
    return(which.max(devs)) #返回最大值的位置
  }
  return(apply(x,1,findol)) #应用findol找到各种异常值
}

3.4增加或删除矩阵的行或列

#3.4.1改变矩阵的大小
x=c(12,3,4,5,2,33)
c(x,20)
c(x[1:3],33,x[4:6])
x
x[-2:-4] #删除2-4的数

one=(c(1,1,1,1))
one
z=matrix(c(1:4,1,1,0,0,1,0,1,0),ncol=3)
z
cbind(one,z)
cbind(1,z)#循环补齐

cbind(c(1,2),c(3,4))#快速生成矩阵
#循环每次往矩阵添加一行和列做法不可取,最好开始定义一个空的大矩阵
m=matrix(1:6,nrow=3)
m[c(1,3),]

#3.4.2扩展案例:找到图中距离最近的一对端点
# returns the minimum value of d[i,j], i != j, and the row/col attaining
# that minimum, for square symmetric matrix d; no special policy on ties
mind <- function(d) {
   n <- nrow(d)
   # add a column to identify row number for apply()
   dd <- cbind(d,1:n)
   wmins <- apply(dd[-n,],1,imin)
   # wmins will be 2xn, 1st row being indices and 2nd being values
   i <- which.min(wmins[2,])
   j <- wmins[1,i]
   return(c(d[i,j],i,j))
}

# finds the location, value of the minimum in a row x
imin <- function(x) {
   lx <- length(x)
   i <- x[lx]  # original row number
   j <- which.min(x[(i+1):(lx-1)])
   k <- i+j
   return(c(k,x[k]))
}

3.5向量与矩阵的差异

z=matrix(1:8,nrow=4)
z
length(z) #矩阵就是一个向量
class(z)
attributes(z)
dim(z)
nrow(z)#对dim的简单封装
ncol(z)

3.6避免意外的降维

z=matrix(1:8,nrow=4)
r=z[2,]
r#r是向量不是1x2的矩阵
attributes(z)
dim(z)

#r已经是向量了
attributes(r)
dim(r)
str(r)
str(z)
#避免减少维度使用drop参数
z[2,,drop=F] #就是矩阵了不是向量
dim(z[2,,drop=F])

#[也是个函数
"["(z,3,2)
z[3,2]

#将向量转化为矩阵
u=c(1,2,3)
u
as.matrix(u)
attributes(u)
attributes(as.matrix(u))

3.7矩阵的行和列的命名问题

z=matrix(1:4,ncol=2)
colnames(z)
colnames(z)=c("a","b")
z
colnames(z)
z[,"a"]

3.8高维数组

firsttest=matrix(1:6,ncol=2)
secondtest=matrix(7:12,ncol=2)
tests=array(data=c(firsttest,secondtest),dim=c(3,2,2))
tests
attributes(tests)
tests[3,2,1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值