个人查漏补缺,以下全部内容均翻译自 An Introduction to R ,原文链接:
https://cran.r-project.org/doc/manuals/r-release/R-intro.html#The-R-environment
2.1 Vectors and assignment
Assignment can also be made using the functionassign(). Anequivalent way of making the same assignment as above is with:(将值依次赋给x)
> assign("x", c(10.4, 5.6, 3.1, 6.4, 21.7))等同于
> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x
> x[1]
> 1/x #得到5个结果
> y <- c(x, 0, x)
> y #得到11个结果 [1] 10.4 5.6 3.1 6.4 21.7 0.0 10.4 5.6 3.1 6.4 21.7
通过以上的方式,可以批量处理一些繁琐的数据,无需单独写循环语句.
2.3 Generating regular sequences 生成规则数据集
举个例子
> seq(-5, 5, by=.2) -> s3 生成从-5开始,5结束,步长为0.5的数据集,等同于:
> s4 <- seq(length=51, from=-5, by=.2)
rep()函数, 生成重复数据集.
> s5 <- rep(x, times=5)
> s6 <- rep(x, each=5)
2.4 Logical vectors逻辑型向量
> x
[1] 10.4 5.6 3.1 6.4 21.7
> temp <- x > 13
> temp
[1] FALSE FALSE FALSE FALSE TRUE
2.5 Missing values缺失值
> z <- c(1:3,NA); ind <- is.na(z)#返回逻辑向量
> z
[1] 1 2 3 NA
> ind
[1] FALSE FALSE FALSE TRUE
2.6 Character vectors 特征型向量
> labs <- paste(c("X","Y"), 1:10, sep="")
添加特征型向量: c("X1", "Y2", "X3", "Y4", "X5", "Y6", "X7", "Y8", "X9", "Y10")
3.4 The class of an object
"numeric","logical","character"or"list",
but"matrix","array","factor"and"data.frame"are other possible values.
假定class是一个数据框,unclass函数将会打印成一个传统的列表.
> unclass(winter)
4 Ordered and unordered factors 因子排序
举个例子
state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa", "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas", "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa", "sa", "act", "nsw", "vic", "vic", "act")
statef <- factor(state)
> statef
[1] tas sa qld nsw nsw nt wa wa qld vic nsw vic qld qld sa
[16] tas sa nt wa vic qld nsw nsw wa sa act nsw vic vic act
Levels: act nsw nt qld sa tas vic wa
> levels(statef)
[1] "act" "nsw" "nt" "qld" "sa" "tas" "vic" "wa"
4.2 The functiontapply()and ragged arrays
继续之前的例子,重新赋予一些值给statef,
> incomes <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,
61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,
59, 46, 58, 43)
使用函数 tapply() 计算均值:
> incmeans <- tapply(incomes, statef, mean)
act nsw nt qld sa tas vic wa
44.500 57.333 55.500 53.600 55.000 60.500 56.000 52.250
> stdError = function(x) sqrt(var(x)/length(x))
> incmeans <- tapply(incomes, statef, stdError)
6.3.2attach() and detach()
attach() 函数处理列表list or 数据框dataframe.假定lentils 这个数据框有三个变量 lentils$u,lentils$v,lentils$w.
> attach(lentils) #函数执行类似下面的操作:
> u <- v+w
> lentils$u <- v+w
To detach a data frame, use the function
> detach()
6.3.5 Managing the search path
> search()
[1] ".GlobalEnv" "Autoloads" "package:base"
ls(2)