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
> #求A和B的并集
> union(A,B)
[1] 1 2 3 4 5 6 7 8 910 11 13 15
> #求A和B的交集
> 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)