R语言编程艺术学习笔记(矩阵、数组、列表)

来源:互联网 发布:java web的书 编辑:程序博客网 时间:2024/05/09 21:38

3.2.3图像操作

一张灰度图像会把每一个像素点的亮度存储为矩阵的一个元素。如果图像是彩色的话,就需要三个矩阵来存储,分别记录红、黄、蓝的强度值。这里我们以灰度图像为例。

我们用pixmap包来读取图像。

library(pixmap)mtrush1<-read.pnm("mtrush1.pgm")

读取文件mtrush1.pgm,并返回一个pixmap类的对象。

在图片加上随机噪声

bluepart<-function(img,rows,cols,q){   lrows<-length(rows)   lrows<-length(cols)   newing<-img   randomnoise<-matrix(nrow=lrows,ncol=ncols,runif(lrows*lcols))#runif是产生均匀分布的数   nnewimg@grey<-(1-q)*img@grey+q*randomnoise   return(newing)}
注意这里代码有点问题,具体到时可以再斟酌

使用apply函数

apply(m,dimcode,f,fargs)
m是一个矩阵

dimcode是维度编号,若取值为1代表对每一行应用函数,若取值为2代表对每一列应用函数

f是应用在行和列上的函数

frags是f的可选参数集

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 tiesmind<-function(d){  n<-nrow(d)  dd<-cbind(d,1:n)  wmins<-apply(dd[-n,],1,imin)   i<-which.min(wmins[2,])   j<-wmins[1,i]   return(c(d[i,j],i,j))}#finds the location ,value of 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]))}
首先找到每行最小值的那一个,然后找到最小值最小的那一个

如果矩阵中最小值是唯一的,还有一种更简单的方法:

minda<-function(d){     samllest<-min(d)     ij<-which(d=smallest,arr.ind=TRUE)     return(c(smallest,ij))}
还有一个效率问题。这段代码实质上包含两个(隐形的)循环:一个是计算最小值smallest,另一个是调用which().因此新的代码会比原来的慢

3.6避免意外降维

R有办法禁止矩阵自动减少维度:使用drop函数

r<-z[2,,drop=FALSE]
3.8高维数组

除了行和列,还有第三个维度的呗成为高维数组(arrays)

可以把两个矩阵合并成一个三维数组,同样也可以把三维数组合并成一个思维数组。

4.1创建列表

j<-list(name="Joe",salary=55000,union=T)
列表索引

j$salaryj[["salary"]]j[[2]]
4.2.3

文本词汇索引


findwords<-function(tf){     #read in the words from the file ,into a vector of mode charater     txt<-scan(tf,"")     wl<-list()     for(i in 1 length(txt)){        wrd<-txt[i]# ith word in input file        wl[[wrd]]<-c(wl[[wrd]],i)   }   return(wl)}
4.4.2文本词汇索引(序)

根据字母顺序排序

#sorts wrdlst, the output of findwords() alphabetically by wordalphawl<-funtion(wrdlst){     nms<-names(wrdlst)#the words     sn<-sort(nms)     return(wrdlst[sn])}
根据字母排序

#orders the output of findwords() by word frequency freqwl<-function(wrdlst){    freqs<-sapply(wrdlst, length)#get word frequencies    return(wrdlst[order(freqs)])}

order返回的是排序后向量的原向量的索引




0 0