【R】《R语言入门与实践》读书笔记

2020-11-30  本文已影响0人  韦子谦

最近在学习R,主要在看《R语言入门与实践》这本书(Garrett Grolemund著,冯凌秉译,人民邮电出版社),做了一些笔记,分享给大家

目录

这篇笔记的PDF版本:https://pan.baidu.com/s/1PB874TCKAWOP65TM6euFPg
提取码:08kx

第一部分

第一章 R基础

1.1 下载、安装R和RStudio

1.2 将R当成一个计算器

> 5*(7^2+1)-3
[1] 247

1.3 对象

> a <- 5*(7^2+1)-3
> a
[1] 247

1.4 函数

> mean(1:6)
[1] 3.5
> round(mean(1:6))
[1] 4
> sample(1:6,size=2)
[1] 5 3
> args(sample)
function (x, size, replace = FALSE, prob = NULL) 
NULL
> #自定义函数:计算t检验的效应量
> conhens_d <- function(m1, m2, s) {
+   d <- (m1-m2)/s
+   return(d)
+ }

> #调用自定义函数
> conhens_d(23,21,2.5)
[1] 0.8

1.5 脚本

第二章 R包与帮助系统

2.1 R包

install.packages('ggplot2')
library('ggplot2')
> qplot
function (x, y, ..., data, facets = NULL, margins = FALSE, geom = "auto", 
    xlim = c(NA, NA), ylim = c(NA, NA), log = "", main = NULL, 
    xlab = NULL, ylab = NULL, asp = NA, stat = NULL, position = NULL) 
{
    ...
}
> x <- c(-1,-.8,-.6,-.4,-.2,0,.2,.4,.6,.8,1)
> y <- x^3
> qplot(x,y)
update.packages(c('ggplot2','reshape2','dplyr'))

2.2 从帮助页面获取帮助

?qplot
简介
描述(Description) 一段简短的有关该函数功能的描述
用法(Usage) 告诉我们如何键入该函数和相应的参数名
参数(Arguments) 列出该函数所包含的所有参数、各参数接受的赋值类型以及参数的作用
相关细节(Details) 对函数的工作原理的进一步描述,通常会提到一些使用函数时的注意事项
返回值(Value) 一段关于该函数运行后的返回值的简短描述
另请参阅(See also) 与该函数相关的函数的列表
示例(Examples) 确保可以无错运行的代码示例
??plot

2.3 获取更多的帮助

第二部分

第三章 R对象

3.1 原子型向量

> x <- c(3,-2,4,7,5,-1,0)
> x
[1]  3 -2  4  7  5 -1  0
> is.vector(x)
[1] TRUE
> length(x)
[1] 7
简介
double(双整数型) 也称为数值型(numeric),这个是R中默认的向量类型,例如上述例子中的向量x就属于double
integer(整数型) 储存整数数值,定义方法:在数值后加一个大写的L,例如y=c(1L, 2L, 3L) ,integer可以避免在double中可能出现的浮点误差问题(例如sqrt(2)^2-2的输出结果不为0)
character(字符型) 储存文本,也称字符串(string),定义方法:添加单引号或双引号,例如text=c('hello','world')。字符串也可以是数字,例如text=c('1','2','3'),但character向量无法进行四则运算
logical(逻辑型) 定义方法:大写的TRUE和FALSE,例如logic=c(TRUE, FALSE, TRUE)
complex(复数类型)和raw(原始类型) conplex向量用于储存复数,raw向量用于储存数据的原始字节
> x <- c(3,-2,4,7,5,-1,0)
> names(x) <- c('one','two','three','four','five','six','seven')
> x
  one   two three  four  five   six seven 
    3    -2     4     7     5    -1     0 
> x <- 1:6
> x
[1] 1 2 3 4 5 6
> x <- (1:6)*0.3
> x
[1] 0.3 0.6 0.9 1.2 1.5 1.8

3.2 矩阵

> a <- c(1,2,3,4,5,6)
> m <- matrix(a,nrow=2,ncol=3)
> m
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

3.3 数组

> a <- array(c(1:24), dim=c(2,3,4))
> a
, , 1

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

, , 2

     [,1] [,2] [,3]
[1,]    7    9   11
[2,]    8   10   12

, , 3

     [,1] [,2] [,3]
[1,]   13   15   17
[2,]   14   16   18

, , 4

     [,1] [,2] [,3]
[1,]   19   21   23
[2,]   20   22   24

3.4 类

> class(a)
[1] "array"
> now <- Sys.time()
> now
[1] "2020-11-03 20:35:47 CST"
> typeof(now)
[1] "double"
> class(now)
[1] "POSIXct" "POSIXt" 
> gender <- factor(c('male','female','female'))
> attributes(gender)
$levels
[1] "female" "male"  

$class
[1] "factor"

3.5 强制转换

> as.character(1)
[1] "1"
> as.logical(1)
[1] TRUE
> as.double(TRUE)
[1] 1

3.6 列表

> my_list <- list(1:10, 'text', TRUE)
> my_list
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
[1] "text"

[[3]]
[1] TRUE

3.7 数据框

> students <- data.frame(name=c('harry','ron','hermione'), gender=c('male','male','female'),age=c(17,17,17))
> students
      name gender age
1    harry   male  17
2      ron   male  17
3 hermione female  17
> students$gender
[1] "male"   "male"   "female"

3.8 加载和保存数据

3.8.1 R基础包中的数据集
help(packages='datasets')
3.8.2 工作目录
> getwd()
[1] "C:\Users\韦子谦\Documents"
> setwd('D:/R_project')
3.8.3 读取和写入纯文本文件
data1 <- read.table('data.csv',sep=',',header=TRUE,na.strings='.',skip=3,nrow=5,stringsAsFactors=FALSE)
options(stringsAsFactors=FALSE)
默认设置 使用情形
read.table sep=" ", header=FALSE 通用读取函数
read.csv sep=",", header=TRUE 逗号分隔值(csv)的文件
read.delim sep="\t", header=TRUE 制表符分隔的文件(制表符就是Tab键敲出的那个符号,相当于缩进)
read.csv2 sep=";", header=TRUE, dec="," 欧式小数点符号的csv文件
read.delim2 sep="\t", header=TRUE, dec="," 欧式小数点符号的制表符分隔的文件
文件格式 函数及其使用方法
csv write.csv(r_object, file=filepath, row.names=FALSE)
欧式小数点符号的csv write.csv2(r_object, file=filepath, row.names=FALSE)
制表符分隔 write.table(r_object, file=filepath, sep="\t", row.names=FALSE)
write.csv(data1, file=bzfile("data1.csv.bz2"), row.names=FALSE)
read.csv("data1.csv.bz2")
3.8.4 读取和写入R文件
data1 <- readRDS("data1.RDS")
load("data1.RData")
save(a,b,c,file="data1.RData")
3.8.5 读取Excel
3.8.6 从其它程序加载文件
文件格式 函数 R包
ERSI ArcGIS read.shapefile shapefiles
MATLAB readMat R.matlab
minitab read.mtp foreign
SAS(永久性数据集) read.ssd foreign
SAS(XPORT格式) read.xport foreign
SPSS read.spss foreign
Stata read.dta foreign
Systat read.systat foreign
3.8.7 从数据库中读取数据

第四章 R的记号体系

4.1 正整数

> students <- data.frame(name=c('harry','ron','hermione'), gender=c('male','male','female'),age=c(17,17,17))
> students
      name gender age
1    harry   male  17
2      ron   male  17
3 hermione female  17
> students[1,1]
[1] harry
> students[1:2,1]
[1] harry ron 
> students[1,]  # 提取第一行
   name gender age
1 harry   male  17
> students[,1]  # 提取第一列
[1] harry    ron      hermione

4.2 负整数

> students[-1,]
      name gender age
2      ron   male  17
3 hermione female  17

4.3 零索引

> students[0,0]
data frame with 0 columns and 0 rows

4.4 空格索引

4.5 逻辑值索引

> students[c(TRUE, FALSE,TRUE),2]
[1] male   female

4.6 名称索引

> students[1:3, 'name']
[1] harry    ron      hermione

4.7 美元符号和双中括号

> students$name
[1] harry    ron      hermione
> l <- list(c(1,2,3), c(TRUE, FALSE))
> l
[[1]]
[1] 1 2 3

[[2]]
[1]  TRUE FALSE

> l[1]
[[1]]
[1] 1 2 3

> l[[1]]
[1] 1 2 3

第五章 对象改值

5.1 就地改值

> x <- c(1,2,3,4,5)
> x[1] <- 100
> x
[1] 100   2   3   4   5
> x[1:3] <- c(100,200,300)
> x
[1] 100 200 300   4   5
> x[6] <- 6
> x
[1] 100 200 300   4   5   6
> students <- data.frame(name=c('harry','ron','hermione'), gender=c('male','male','female'),age=c(17,17,17))
> students$new <- 1:3
> students
      name gender age new
1    harry   male  17   1
2      ron   male  17   2
3 hermione female  17   3
> students$new <- NULL
> students
      name gender age
1    harry   male  17
2      ron   male  17
3 hermione female  17

5.2 逻辑取子集

5.2.1 逻辑测试
运算符 语法 判别
> a>b a是否大于b?
>= a>=b a是否大于或等于b?
< a<b a是否小于b?
<= a<=b a是否小于或等于b?
== a==b a是否等于b?
!= a!=b a是否不等于b?
%in% a %in% c(a,b,c) c(a,b,c) 中是否包含a?
> 3 > c(1,2,3,4,5)
[1]  TRUE  TRUE FALSE FALSE FALSE
> a <- c('group1','group2','group1','group2')
> b <- c(0.586, 0.762, 0.462, 0.631)
> a=='group1'
[1]  TRUE FALSE  TRUE FALSE
> b[a=='group1']
[1] 0.586 0.462
> b[a=='group1' & b>0.5]
[1] 0.586
5.2.2 布尔运算符
运算符 语法 判别
& cond1 & cond2 cond1和cond2是否同时为真?
| cond1 pipe cond2 cond1和cond2是否至少有一个为真?
xor xor(cond1,cond2) cond1和cond2中是否只有一个为真?
! !cond1 cond1是否为假?
any any(cond1,cond2,cond3, ...) 所有条件是否至少有一个为真?
all all(cond1,cond2,cond3, ...) 所有条件是否同时为真?
> any(1>2, 'yes'=='no',2*2==4)
[1] TRUE
5.2.3 缺失信息
> 1+NA
[1] NA
> mean(c(1,2,3,NA))
[1] NA
> mean(c(1,2,3,NA),na.rm = TRUE)
[1] 2
> is.na(NA)
[1] TRUE
> is.na(c(1,2,3,NA))
[1] FALSE FALSE FALSE  TRUE
> any(is.na(c(1,2,3,NA)))
[1] TRUE

第六章 R的环境系统

6.1 R的环境系统

deal <- function(){
  print(x)
}

x <- 'hello'
deal()

第三部分

第七章 程序

7.1 策略

7.2 if和else语句

if (this) {
  plan A
} else if (that) {
  plan B
} else {
  plan C
}

第八章 S3

> n <- 1000000000
> class(n)
[1] "numeric"
> n
[1] 1e+09
> class(n) <- c("POSIXct", "POSIXt")
> class(n)
[1] "POSIXct" "POSIXt" 
> n
[1] "2001-09-09 09:46:40 CST"

8.1 属性

> gender <- factor(c('male','female','female'))
> attributes(gender)
$levels
[1] "female" "male"  

$class
[1] "factor"
> attributes(n)
$class
[1] "POSIXct" "POSIXt" 
> attr(n, 'Hello') <- "World"
> attributes(n)
$class
[1] "POSIXct"

$Hello
[1] "World"

8.2 泛型函数

8.3 方法

> methods(print)
  [1] print.acf*                                          
  [2] print.anova*                                        
  [3] print.aov*
  ...
  [183] print.xgettext*
  [184] print.xngettext*
  [185] print.xtabs* 

8.4 小结

第九章 循环

9.1 for循环

for (value in that) {
  this
}

9.2 while循环

while (condition) {
  code
}

9.3 repeat循环

repeat{
  code
  if (this) {
    break
  }
}

9.4 小结

第十章 代码提速

10.1 向量化代码

> state.division
 [1] East South Central Pacific            Mountain          
 [4] West South Central Pacific            Mountain          
 [7] New England        South Atlantic     South Atlantic    
[10] South Atlantic     Pacific            Mountain          
[13] East North Central East North Central West North Central
[16] West North Central East South Central West South Central
[19] New England        South Atlantic     New England       
[22] East North Central West North Central East South Central
[25] West North Central Mountain           West North Central
[28] Mountain           New England        Middle Atlantic   
[31] Mountain           Middle Atlantic    South Atlantic    
[34] West North Central East North Central West South Central
[37] Pacific            Middle Atlantic    New England       
[40] South Atlantic     West North Central East South Central
[43] West South Central Mountain           New England       
[46] South Atlantic     Pacific            South Atlantic    
[49] East North Central Mountain          
9 Levels: New England Middle Atlantic ... Pacific
# 非向量化的代码
count_loop <- function(){
  count <- 0
  for (i in 1:length(state.division)) {
    if (state.division[i] == "New England") {
      count <- count + 1
    }
  }
  return(count)
}
> count_loop()
[1] 6
# 向量化的代码
count_set <- function(){
  count <- length(state.division[state.division == "New England"])
  return(count)
}
> state.division == "New England"
 [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
[11] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[21]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[31] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[41] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
> state.division[state.division == "New England"]
[1] New England New England New England New England New England
[6] New England
# 向量化的代码
count_set <- function(){
  count <- sum(state.division == "New England")
  return(count)
}

10.2 如何编写向量化的代码

10.3 如何在R中编写快速的for循环

10.4 调试R代码

10.4.1 traceback
10.4.2 browser
10.4.3 断点
10.4.4 debug
10.4.5 trace
trace("deal",browser,at=4)
10.4.6 recover
options(error=recover)
options(error=NULL)

 

----------2020.12.06更新----------
添加了第6、7、9、10章的笔记
----------2020.12.07更新----------
添加了第8章的笔记
----------2020.12.14更新----------
添加了第2章和附录部分的内容,修正了诸多表述和错字
----------2020.12.2更新----------
添加了目录

上一篇下一篇

猜你喜欢

热点阅读