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() 判断向量中有没有缺失值,有缺失值的位置返回FALSE
  • is.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()

    • 其中需要注意:

      mean(x, trim = FALSE)

      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)

x <- rev(rep(6:10, 1:5))
rle(x)
## lengths [1:5]  5 4 3 2 1
## values  [1:5] 10 9 8 7 6

4.1.5 编写函数

  • function()missing 用法 function(x,y){if(missing(y)) ...}
  • on.exit() 用于函数内部,指定在函数运行结束时(不论是正常结束还是遇到错误)需要执行的代码,常用来清空绘图面板之类的操作
  • return(), invisible()
  • flush.console() 用于使打印在屏幕上的输出结果覆盖上一个

4.1.6 逻辑与集合

  • &, |, !, xor

  • all(), 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)

# 例:给数组x的第一行都加1,第二行都加4,第三行都加7
sweep(x, 1, c(1,4,7), "+")

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, while
  • next, break
  • switch()
  • ifelse()

4.1.10 apply族

  • lapply(), sapply(), vapply()()
  • apply()
  • tapply()
  • replicate() 将sapply的结果重复指定次数

4.2 常见数据结构

4.2.1 Date time

  • ISOdate, ISOdatetime, strftime, strptime, date
  • difftime
  • julian, months, quarters, weekdays
  • library(lubridate)

4.2.2 Character manipulation

  • grep, agrep
  • gsub
  • strsplit
  • chartr(old,new,x) 将x中的字符串old替换成new
  • nchar
  • tolower, toupper
  • substr
  • paste
  • trimws Remove Leading/Trailing Whitespace
  • library(stringr)

4.2.3 Factors

  • factor, levels, nlevels
  • reorder, relevel
  • cut, findInterval
  • interaction
  • options(stringsAsFactors = FALSE)

4.2.4 Array manipulation

  • array
  • dim
  • dimnames
  • aperm 调整一个数组的维度
  • library(abind)

4.3 统计函数

4.3.1 排序和制表

  • duplicated, unique
  • merge
  • order, rank, quantile
  • sort
  • table, ftable

4.3.2 Linear models

  • fitted, predict
  • resid extracts model residuals from objects returned by modeling functions
  • rstandard
  • lm, glm
  • hat, influence.measures
  • logLik, df, deviance
  • formula, ~, I
  • anova, coef, confint 计算某一个参数的置信区间
  • vcov Calculate Variance-Covariance Matrix for a Fitted Model Object
  • contrasts

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) %*% y
  • tcrossprodx %*% t(y)
  • eigen 计算矩阵特征值和特征向量
  • qr 矩阵的QR分解
  • svd 矩阵的奇异值分解
  • %*% 矩阵的内积
  • %o%, outer 矩阵的外积
  • rcond
  • solve 解方程组

4.4 使用R

4.4.1 Workspace

  • ls, exists, rm
  • getwd, setwd
  • q, quit
  • source
  • install.packages, library, require

4.4.2 Help

  • help, ?
  • help.search, ??
  • apropos
  • RSiteSearch
  • citation
  • demo
  • example
  • vignette

4.4.3 Debugging

  • traceback Get and Print Call Stacks
  • browser
  • recover
  • options(error = ) 可选stop, warning, message
  • tryCatch, try

4.5 I/O函数

4.5.1 Output

  • print, cat
  • message, warning
  • dput 将R对象以ASCII文本表示形式写入文件或连接,或使用ASCII文本表示形式重新创建该对象
  • format
  • sink 将R在屏幕上的输出保存在文件中
  • capture.output 将屏幕上的输出结果保存成一个字符串变量
  • sprintf

4.5.2 Reading and writing data

  • data 加载一个内置的数据集
  • count.fields
  • read.csv, write.csv 默认读写以逗号为分隔符的table文件
  • read.delim, write.delim 默认读写以TAB为分隔符的table文件
  • read.fwf 读取以等间隔为分隔符的table文件
  • readLines, writeLines
  • readRDS, saveRDS
  • load, save
  • library(foreign)
  • library(data.table)
  • library(readxl)

4.5.3 Files and directories

  • dir
  • basename, dirname, tools::file_ext
  • file.path
  • path.expand, normalizePath
  • file.choose Choose a file interactively
  • file.copy, file.create, file.remove, file.rename, dir.create
  • file.exists, file.info
  • tempdir
  • tempfile returns a vector of character strings which can be used as names for temporary files.
  • download.file, library(downloader)