R語言基礎編程技巧彙編 - 7

1.      &和&&區別和聯繫

&是按照向量來計算的,對兩個向量的每一對應值都會進行“邏輯與”運算,返回值是一個含多個分量的布爾值向量;而&&只對向量的第一個分量進行“邏輯與”運算,返回值是一個布爾值。同理,|||也類似。

例如:

A<- 1:5

A

#[1]1 2 3 4 5

B<- -2:2

 

B

#[1]-2 -1  0 1  2

A& B

#[1]  TRUE TRUE FALSE  TRUE  TRUE

A&& B

#[1]TRUE

2.       '+'也是個S3泛型函數

'+'可以根據兩邊的操作數的類型自動選擇合適的操作,它是由R語言核心代碼實現的一個泛型函數。'+'是比較特殊的一類函數,是屬於R語言內置的一類叫做 Group methods Ops組中一員。

'+'是用了一種特殊方法來比較函數的兩個參數,然後根據兩個參數的類別,來確定函數的使用。具體可以看R語言的定義中寫的。

‘Ops’

+,-, *, /, ^, < , >, <=, >=, !=, ==, %%, %/%, &, |, !

Foroperators in the Ops group a special method is invoked if the two operandstaken together suggest a single method. Specifically, if both operandscorrespond to the same method or if one operand corresponds to a method thattakes precedence over that of the other operand. If they do not suggest asingle method then the default method is used. Either a group method or a classmethod dominates if the other operand has no corresponding method. A classmethod dominates a group method.

Whenthe group is Ops the special variable .Method is a string vector with twoelements. The elements of .Method are set to the name of the method if thecorresponding argument is a member of the class that was used to determine themethod. Otherwise the corresponding element of .Method is set to the zerolength string, “”.

 

可以通過methods來獲取S3泛型函數。

>methods('+')

[1]+.Date   +.POSIXt

還可以通過getS3method來獲取函數定義。一下是+.Date的定義,可以爲你寫函數提供參考。

>getS3method('+','Date')

function(e1, e2)

{

    coerceTimeUnit <- function(x)as.vector(round(switch(attr(x,

        "units"), secs = x/86400, mins= x/1440, hours = x/24,

        days = x, weeks = 7 * x)))

    if (nargs() == 1)

        return(e1)

    if (inherits(e1, "Date")&& inherits(e2, "Date"))

        stop("binary + is not defined for\"Date\" objects")

    if (inherits(e1, "difftime"))

        e1 <- coerceTimeUnit(e1)

    if (inherits(e2, "difftime"))

        e2 <- coerceTimeUnit(e2)

    structure(unclass(e1) + unclass(e2), class= "Date")

}

<bytecode:0x0000000012fcd1b0>

<environment:namespace:base>

 就好比

"+"(1L,2.)

第一個參數找到.integer方法(也許有.double方法,但我們假設沒有),第二個.double,不一致,然後調用內部方法,這個內部方法能做什麼??它是什麼?它就可以把不同類型加起來麼

你看下是你想要的:

Ops.numeric_version

下面這個是其它類的:

Ops.data.frame

C那樣Type conversions(強制類型轉換)的故事你只是想多了,R單純

as.numeric_version

.encode_numeric_version

也就是做代數運算的時候也是多次轉換的結果。

3.      '='和'<-'的區別

多數情況下,兩者可以互相替代,只有在函數參數列表

給兩個例子就明白了:

比如,plot(x<-1:10)

就是在作圖之前把1:10賦給x,這個表達式在繪圖之前就被執行了,,相當於

x<-1:10

plot(x)

 

所以,作完圖之後變量x也就有值了。

而你用plot(x=1:10)就不能達到對x賦值的目的,這時表達的含義是,爲plot函數中名字爲x的形式參數賦值1:10,作完圖之後,x這個對象仍然不存在。

只有在函數外部直接執行x=1:10才能達到對x賦值的目的。

plot(x=1:10)#x是形式參數,不是新變量

x

#錯誤:找不到這個對象"x"

 

#<-不會用於形式參數,所以這是爲新變量x賦值的語句,不會引起歧義

plot(x<-1:10)

x

#[1]1 2 3 4 5 6 7 8 9 10

總之,<-在任何地方都可以完成賦值的工作,而=在函數參數列表則不行,所以,推薦任何時候都用<-進行賦值操作,=僅用於形式參數。

4.      多元正態分佈隨機數

library(MASS)

Sigma<- matrix(c(10,3,3,2),2,2)

Sigma

mvrnorm(n=1000,rep(0, 2), Sigma)

5.       在圖形裏面添加公式文本

plot(0)

text(1,0,as.expression(paste(fm[[1]][1],"=", c[1],"+",c[2],"*",fm[[1]][3])))

 

更復雜的情況請查看plotmath的幫助

6.      unlist函數的作用

list類型的數據,轉化爲原子類型的向量,形象的比喻爲“拆包”。例如:

A<- list(LETTERS)

A

#[[1]]

#[1]"A" "B" "C" "D" "E""F" "G" "H" "I" "J""K" "L" "M" "N" "O""P" "Q"#"R" "S" "T""U" "V" "W" "X" "Y""Z"

unlist(A)

#[1]"A" "B" "C" "D" "E""F" "G" "H" "I" "J""K" "L" "M" "N" "O""P" "Q"#"R" "S" "T""U" "V" "W" "X" "Y""Z"

7.       集合運算

#首先對集合A,B,C賦值

> A<-1:10

> B<-seq(5,15,2)

> C<-1:5

> #AB的並集

> union(A,B)

[1]  1  2  3  4  5  6  7  8  910 11 13 15

> #AB的交集

> intersect(A,B)

[1] 5 7 9

> #A-B

> setdiff(A,B)

[1]  1  2  3  4  6  810

> #B-A

> setdiff(B,A)

[1] 11 13 15

> #檢驗集合A,B是否相同

> setequal(A,B)

[1] FALSE

> #檢驗元素12是否屬於集合C

> is.element(12,C)

[1] FALSE

> #檢驗集合A是否包含C

> all(C%in%A)

[1] TRUE

> all(C%in%B)

[1] FALSE

 

 

8.       使用rm函數清除變量

例如,

> A <- 0

> A

[1] 0

> rm(A)

> A

Error: object 'A' not found

 

又比如,清除所有變量,慎用:

rm(list = ls())

9.      繪製K線圖

library(quantmod)

getSymbols("YHOO")

 

#add volume and Bollinger Bands fromTTR

chartSeries(YHOO,TA=c(addVo(),addBBands())) 

 

10. 去掉標籤legend的外框

bty="n"

 

11. 去除向量中的NA

方法一:

dt <- c(1,23,23,NA,23,1333,333,NA)

dt[complete.cases(dt)]

 

方法二:

#向量名命名爲h

h<-c(1,23,23,NA,23,1333,333,NA)

h[!is.na(h)]

#is.na判定一下再取非就可以了

 

方法三:

a<-c(1,23,23,NA,23,1333,333,NA)

> a

[1]    1  23   23   NA   23 1333  333  NA

> a<-a[-which(is.na(a))]

> a

[1]    1  23   23   23 1333  333

 

方法四:

>a<-c(1,23,23,NA,23,1333,333,NA)

> na.omit(a)

[1]   1   23   23  23 1333  333

attr(,"na.action")

[1] 4 8

attr(,"class")

[1] "omit"

 

12. 生成eps文件

postscript(file ="plot.eps")

plot(1:10)

dev.off()

13. 一次性加載所有的程序包

把加載包的程序代碼寫到一個文件裏,比如Header.R

內容如下:

library(MASS)

library(ggplot2)

library(quantmod)

library(stringr)

library(rgl)

 

需要加載這些包時,用source函數執行這個源代碼即可。

14. 判別對稱矩陣

直接用isSymmetric(x)

或者all(x - t(x)==0),這裏x是你的矩陣

 

15. 繪製等高線圖

require(grDevices) # for colours

x <- -6:16

op <- par(mfrow = c(2, 2))

contour(outer(x, x), method ="edge", vfont = c("sans serif", "plain"))

z <- outer(x, sqrt(abs(x)), FUN ="/")

image(x, x, z)

contour(x, x, z, col ="pink", add = TRUE, method = "edge",vfont = c("sansserif", "plain"))

contour(x, x, z, ylim = c(1, 6),method = "simple", labcex = 1, xlab = quote(x[1]), ylab =quote(x[2]))

contour(x, x, z, ylim = c(-6, 6),nlev = 20, lty = 2, method = "simple", main = "20 levels;\"simple\" labelling method")

par(op)

 

## Persian Rug Art:

x <- y <- seq(-4*pi, 4*pi, len= 27)

r <- sqrt(outer(x^2, y^2,"+"))

opar <- par(mfrow = c(2, 2), mar =rep(0, 4))

for(f in pi^(0:3))

 contour(cos(r^2)*exp(-r/f), drawlabels = FALSE, axes = FALSE, frame =TRUE)

 

rx <- range(x <-10*1:nrow(volcano))

ry <- range(y <-10*1:ncol(volcano))

ry <- ry + c(-1, 1) * (diff(rx) -diff(ry))/2

tcol <- terrain.colors(12)

par(opar); opar <- par(pty ="s", bg = "lightcyan")

plot(x = 0, y = 0, type ="n", xlim = rx, ylim = ry, xlab = "", ylab = "")

u <- par("usr")

rect(u[1], u[3], u[2], u[4], col =tcol[8], border = "red")

contour(x, y, volcano, col = tcol[2],lty = "solid", add = TRUE,vfont = c("sans serif","plain"))

title("A Topographic Map of MaungaWhau", font = 4)

abline(h = 200*0:4, v = 200*0:4, col= "lightgray", lty = 2, lwd = 0.1)

 

## contourLines produces the samecontour lines as contour

plot(x = 0, y = 0, type ="n", xlim = rx, ylim = ry, xlab = "", ylab = "")

u <- par("usr")

rect(u[1], u[3], u[2], u[4], col =tcol[8], border = "red")

contour(x, y, volcano, col = tcol[1],lty = "solid", add = TRUE,vfont = c("sans serif","plain"))

line.list <- contourLines(x, y,volcano)

invisible(lapply(line.list, lines,lwd=3, col=adjustcolor(2, .3)))

par(opar)




 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章