![](https://img.haomeiwen.com/i22672581/42df2ec7bbc30f04.png)
为什么学这本书:
这本书我刚开始学习R的时候草草看过,名曰经典入门书籍,实则对R零基础非常不友好在学习《R for Data Science》和《Data Analysis for the Life Sciences》两本书时,我发现时常需用编程思想解决核心问题,但前者侧重tidyverse包数据处理,后者已是R统计应用,所以需要一本书帮助我捡起编程思想,以及带我进一步了解R编程的魅力
所以从今天就开始重温这本书,存在即合理
前置知识
- 批处理模式
pdf('dat.pdf')
hist(rnorm(100))
# 关闭正在使用的图形设备
# 实际上就是把文件写入磁盘的机制
dev.off()
- 基础知识点
c 表示连接(英文是concatenate)
x <- c(1,2,4)
y <- c(x,x,3);y
# [1] 1 2 4 1 2 4 3
R向量的索引(下标)是从1开始
y[3]
# [1] 4
x[2:3]
# [1] 2 4
退出R
q()
- 内置数据集
data()
![](https://img.haomeiwen.com/i22672581/7aa2691308bf8442.png)
函数入门
# 统计奇数
oddcount <- function(x) {
k <- 0
for (n in x){
# 取模 %%
if (n %% 2 == 1) k <- k + 1
}
return(k)
}
var <- c(1,2,3,4,5,6,7,9)
oddcount(var)
在上述例子中:
x
:形式参数
var
:实际参数
向量入门
![](https://img.haomeiwen.com/i22672581/5ed0013b706e265b.png)
- 标量
单个的数,实际上是一元向量
- 字符串简单处理
u <- paste('abc','de','f');u
# [1] "abc de f"
v <- strsplit(u,' ')
v # v[1]
# [[1]]
# [1] "abc" "de" "f"
v[[1]]
# [1] "abc" "de" "f"
列表入门
x <- list(u=2,v='abc');x
# $u
# [1] 2
#
# $v
# [1] "abc"
列表的常见用法是把多个值打包组合在一起,然后从函数中返回
hn <- hist(Nile); hn
![](https://img.haomeiwen.com/i22672581/c1c3a59634f1b545.png)
数据框入门
d <- data.frame(list(kids=c('Jack','Jill'),
ages=c(12,10)))
# dataframe内部本质是list构成的,可省略
d <- data.frame(kids=c('Jack','Jill'),
ages=c(12,10))
类入门
以S3类为例
hn <- hist(Nile)
print(hn)
- attribute包含列表的所属类
![](https://img.haomeiwen.com/i22672581/a56f81903959e063.png)
类需要用在泛型函数中,泛型函数代表一个函数族,其中每个函数都有相似的功能,但是适用于某个特定的类,如
summary()
和plot()
拓展案例一
—— 考试成绩的回归分析
examsquiz <- data.frame(
V1 = c(2.0,3.3,4.0,2.3,2.3,2.4,2.4,2.6,3.3,3.1,3.2),
V2 = c(3.3,2.0,4.3,1.2,1.0,2.4,3.2,3.3,1.7,3.2,2.9),
V3 = c(4.0,3.7,4.0,3.3,3.3,4.1,4.0,3.9,2.9,3.3,3.1)
)
# V1 期中,V2 期末,V3 平均小测
# 用期中成绩预测期末成绩
lma <- lm(examsquiz$V2 ~ examsquiz$V1)
![](https://img.haomeiwen.com/i22672581/b25d476b2cd84605.png)
- 可以用attributes列出lm类实例lma的全部组件
attributes(lma)
# $names
# [1] "coefficients" "residuals" "effects" "rank" "fitted.values"
# [6] "assign" "qr" "df.residual" "xlevels" "call"
# [11] "terms" "model"
#
# $class
# [1] "lm"
- 查看结果
lma$coefficients
# (Intercept) examsquiz$V1
# 0.8921636 0.6047314
print(lma) # 等价于 lma
#
# Call:
# lm(formula = examsquiz$V2 ~ examsquiz$V1)
#
# Coefficients:
# (Intercept) examsquiz$V1
# 0.8922 0.6047
- 使用print只返回上述结果是由于泛型函数print调用内部的print.lm()来完成
- 可以用str(lma)查看详细结构,用summary(实际是summa.lm())获取详细摘要
- 多个变量线性拟合
lmb <- lm(examsquiz$V2 ~ examsquiz$V1 + examsquiz$V3)
![](https://img.haomeiwen.com/i22672581/4744aa75b82bd18a.png)
互联网资源
![](https://img.haomeiwen.com/i22672581/592617cc9bc602ee.png)
R包更新
- win
install.packages("installr")
require(installr)
updateR()
- mac
install.packages('devtools')
library(devtools)
install_github('andreacirilloac/updateR')
library(updateR)
updateR(admin_password = 'Admin user password')
网友评论