4 常用函数
4.1 基础函数
4.1.1 两个最常用的
?str()
4.1.2 常用运算符和操作符
%in%match()=<-<<-$[[[head()tail()subset()with()assign()get()(return the value of a named object)
4.1.3 比较
all.equal()近似比较identical()用于条件判断语句中,平时使用的==运算符看似合理,其实不然,因为如果运算符两边的长度不为1,则结果长度就不为1,一旦有其中一个为NA,则结果为NA!=,==,>,>=,<,<=is.na()complete.cases()判断向量中有没有缺失值,有缺失值的位置返回FALSEis.finite()
4.1.4 数学
*,+,-,/,^,%%,%/%abs(),sign()acos(),asin(),atan(),atan2()sin(),cos(),tan()ceiling(),floor(),round(),trunc(),signif()exp(),log(),log10(),log2(),sqrt()max(),min(),prod()(返回其中所有元素的乘积),sum()cummax(),cummin(),cumprod(),cumsum()累积计算diff()pmax(),pmin()range()mean(),median(),cor(),sd(),var()其中需要注意:
trim参数的作用是,当trim = 0.1时,会先删除向量x中最大的10%和最小的10%之后,再计算均值,如果trim > 0.5,则返回的结果是中位数median()
rle()(Compute the lengths and values of runs of equal values in a vector)
4.1.5 编写函数
function()中missing用法function(x,y){if(missing(y)) ...}on.exit()用于函数内部,指定在函数运行结束时(不论是正常结束还是遇到错误)需要执行的代码,常用来清空绘图面板之类的操作return(),invisible()flush.console()用于使打印在屏幕上的输出结果覆盖上一个
4.1.6 逻辑与集合
&,|,!,xorall(),any()intersect(),union(),setdiff(),setequal()(比较集合的相等性)which()() ### 向量和矩阵c(),matrix()自动转换规则 character > double > integer > logical
length(),dim(),ncol(),nrow()cbind(),rbind()names(),colnames(),rownames()t()diag()(生成对角矩阵)sweep()as.matrix(),data.matrix()(将data.frame转成numeric matrix)
4.1.7 构建向量
c()rep(),rep_len()seq(),seq_len(),seq_along()rev()sample()choose()组合factorial()阶乘combn(x,m)#Generate all combinations of the elements of x taken m at a time(is/as).(character/numeric/logical/...)
4.1.8 列表和数据框
list(),unlist()data.frame(),as.data.frame()split()expand.grid()Create a data frame from all combinations of the supplied vectors or factors.
4.1.9 控制流
if,&&,||for,whilenext,breakswitch()ifelse()
4.1.10 apply族
lapply(),sapply(),vapply()()apply()tapply()replicate()将sapply的结果重复指定次数
4.2 常见数据结构
4.2.1 Date time
ISOdate,ISOdatetime,strftime,strptime,datedifftimejulian,months,quarters,weekdayslibrary(lubridate)
4.2.2 Character manipulation
grep,agrepgsubstrsplitchartr(old,new,x)将x中的字符串old替换成newnchartolower,touppersubstrpastetrimwsRemove Leading/Trailing Whitespacelibrary(stringr)
4.2.3 Factors
factor,levels,nlevelsreorder,relevelcut,findIntervalinteractionoptions(stringsAsFactors = FALSE)
4.2.4 Array manipulation
arraydimdimnamesaperm调整一个数组的维度library(abind)
4.3 统计函数
4.3.1 排序和制表
duplicated,uniquemergeorder,rank,quantilesorttable,ftable
4.3.2 Linear models
fitted,predictresidextracts model residuals from objects returned by modeling functionsrstandardlm,glmhat,influence.measureslogLik,df,devianceformula,~,Ianova,coef,confint计算某一个参数的置信区间vcovCalculate Variance-Covariance Matrix for a Fitted Model Objectcontrasts
4.3.3 测试函数
apropos("\\.test$")Find Objects by (Partial) Name
4.3.4 随机变量
- d : density
- p : distribution
- q : quantile
- r : random generation
- (q, p, d, r) * (beta, binom, cauchy, chisq, exp, f, gamma, geom, hyper, lnorm, logis, multinom, nbinom, norm, pois, signrank, t, unif, weibull, wilcox, birthday, tukey)
4.3.5 矩阵运算
crossprod(x,y)矩阵乘积,比用%*%符号要快一点,即t(x) %*% ytcrossprod即x %*% t(y)eigen计算矩阵特征值和特征向量qr矩阵的QR分解svd矩阵的奇异值分解%*%矩阵的内积%o%,outer矩阵的外积rcondsolve解方程组
4.4 使用R
4.4.1 Workspace
ls,exists,rmgetwd,setwdq,quitsourceinstall.packages,library,require
4.4.2 Help
help,?help.search,??aproposRSiteSearchcitationdemoexamplevignette
4.4.3 Debugging
tracebackGet and Print Call Stacksbrowserrecoveroptions(error = )可选stop,warning,messagetryCatch,try
4.5 I/O函数
4.5.1 Output
print,catmessage,warningdput将R对象以ASCII文本表示形式写入文件或连接,或使用ASCII文本表示形式重新创建该对象formatsink将R在屏幕上的输出保存在文件中capture.output将屏幕上的输出结果保存成一个字符串变量sprintf
4.5.2 Reading and writing data
data加载一个内置的数据集count.fieldsread.csv,write.csv默认读写以逗号为分隔符的table文件read.delim,write.delim默认读写以TAB为分隔符的table文件read.fwf读取以等间隔为分隔符的table文件readLines,writeLinesreadRDS,saveRDSload,savelibrary(foreign)library(data.table)library(readxl)
4.5.3 Files and directories
dirbasename,dirname,tools::file_extfile.pathpath.expand,normalizePathfile.chooseChoose a file interactivelyfile.copy,file.create,file.remove,file.rename,dir.createfile.exists,file.infotempdirtempfilereturns a vector of character strings which can be used as names for temporary files.download.file,library(downloader)