统计学习导论之R语言应用(二):R语言基础

统计学习导论(ISLR)


参考资料

The Elements of Statistical Learning
An Introduction to Statistical Learning
统计学习导论(二):统计学习概述
统计学习导论(三):线性回归
统计学习导论(四):分类
统计学习导论之R语言应用(二):R语言基础
统计学习导论之R语言应用(三):线性回归R语言代码实战
统计学习导论之R语言应用(四):分类算法R语言代码实战

—# 1、统计学习库——R语言介绍

1.1 基础命令

R使用函数来执行操作。要运行一个名为funcname的函数我们输入funcname(input1, input2)
,其中的输入(或参数)input1并input2告诉R如何运行该函数。一个函数可以有任意数量的输入。
例如,要创建一个数字向量,我们使用函数c()(用于concatenate)。括号内的任何数字都连接在一起。
以下命令指示R将数字 1、3、2 和 5 连接在一起,并将它们保存为名为 的向量x。当我们输入时x,它会给我们返回向量。

x <- c(1, 3, 2)
x
  1. 1
  2. 3
  3. 2
y <- c(1, 4, 3)
y
  1. 1
  2. 4
  3. 3
length(x)

3

length(y)

3

x + y
  1. 2
  2. 7
  3. 5

该ls()函数允许我们查看迄今为止保存的所有对象(例如数据和函数)的列表。该rm()函数可用于删除我们不想要的任何内容。

ls()
  1. 'x'
  2. 'y'
rm(x,y)
ls()

matrix()函数可用于创建数字矩阵。在我们使用该matrix()函数之前,我们可以了解更多信息

x <- matrix(data = c(1, 2, 3, 4), nrow = 2, ncol = 2)
x
A matrix: 2 × 2 of type dbl
13
24

有时指定传入参数的名称会很有用,否则R将假定函数参数以函数帮助文件中给出的相同顺序传递到函数中。如本示例所示,默认情况下R通过连续填充列来创建矩阵。或者,该byrow = TRUE选项可用于按行的顺序填充矩阵。

matrix(c(1, 2, 3, 4), 2, 2, byrow = TRUE)
A matrix: 2 × 2 of type dbl
12
34

请注意,在上面的命令中,我们没有将矩阵分配给诸如的值x。在这种情况下,矩阵会打印到屏幕上,但不会保存以供将来计算。该sqrt()函数返回向量或矩阵的每个元素的平方根。

x^2
A matrix: 2 × 2 of type dbl
1 9
416

rnorm()函数生成一个随机正态变量向量,第一个参数n是样本大小。每次我们调用这个函数时,都会得到不同的答案。在这里,我们创建了两组相关的数字x和y,并使用该cor()函数计算它们之间的相关性。

x <- rnorm(50)
y <- x + rnorm(50, mean = 50, sd = .1)
cor(x, y)

0.994116841106629

默认情况下,rnorm()创建标准正态随机变量,均值为0 和标准差 1. 但是,可以使用mean和sd参数更改平均值和标准差,如上所示。有时我们希望我们的代码重现完全相同的随机数集;我们可以使用该set.seed()函数来做到这一点。该set.seed()函数采用(任意)整数参数。

set.seed(1303)
rnorm(50)
  1. -1.14397631447974
  2. 1.34212936561501
  3. 2.18539047574276
  4. 0.536392517923731
  5. 0.0631929664685468
  6. 0.502234482468979
  7. -0.000416724686432643
  8. 0.565819840539162
  9. -0.572522688962623
  10. -1.11022500727696
  11. -0.0486871233624514
  12. -0.695656217619366
  13. 0.828917480303335
  14. 0.206652855081802
  15. -0.235674509102427
  16. -0.556310491381104
  17. -0.364754357080585
  18. 0.862355034263622
  19. -0.63077153536771
  20. 0.313602125215739
  21. -0.931495317661393
  22. 0.823867618473952
  23. 0.523370702077482
  24. 0.706921411979056
  25. 0.420204325601679
  26. -0.269052154682033
  27. -1.51031729990999
  28. -0.69021247657504
  29. -0.143471952443572
  30. -1.0135274099044
  31. 1.57327373614751
  32. 0.0127465054882014
  33. 0.872647049887217
  34. 0.422066190530336
  35. -0.0188157916578866
  36. 2.61574896890584
  37. -0.693140174826871
  38. -0.266321780991085
  39. -0.720636441231524
  40. 1.36773420645149
  41. 0.264007332160512
  42. 0.632186807367191
  43. -1.33065098578719
  44. 0.0268888182209596
  45. 1.0406363207788
  46. 1.31202379854711
  47. -0.0300020766733214
  48. -0.250025712488174
  49. 0.0234144856913592
  50. 1.65987065574227
set.seed(3)
y <- rnorm(100)
mean(y)
var(y)
sqrt(var(y))
sd(y)

0.0110355710943715

0.732867501277449

0.856076808047881

0.856076808047881

1.2 画图

plot()函数例如,plot(x, y)生成 中的数字x与 中的数字的散点图y。
有许多附加选项可以传递给plot()函数。例如,传入参数xlab将导致标签上的X-轴。要了解有关该plot()函数的更多信息,
请键入?plot。

x <- rnorm(100)
y <- rnorm(100)
plot(x, y)

在这里插入图片描述

plot(x, y, xlab = "this is the x-axis",
    ylab = "this is the y-axis",
    main = "Plot of X vs Y")

在这里插入图片描述

pdf("Figure.pdf")
plot(x, y, col = "green")
dev.off()

png: 2

seq 函数生成序列,seq(a,b)生成a到b的一个序列,默认步长为1,可以用length定义序列长度,by定义步长

seq(1,10, by = 0.5)
  1. 1
  2. 1.5
  3. 2
  4. 2.5
  5. 3
  6. 3.5
  7. 4
  8. 4.5
  9. 5
  10. 5.5
  11. 6
  12. 6.5
  13. 7
  14. 7.5
  15. 8
  16. 8.5
  17. 9
  18. 9.5
  19. 10
?seq
x <- seq(-pi, pi, length = 50)
x
  1. -3.14159265358979
  2. -3.0133643820147
  3. -2.88513611043961
  4. -2.75690783886451
  5. -2.62867956728942
  6. -2.50045129571433
  7. -2.37222302413923
  8. -2.24399475256414
  9. -2.11576648098904
  10. -1.98753820941395
  11. -1.85930993783886
  12. -1.73108166626376
  13. -1.60285339468867
  14. -1.47462512311358
  15. -1.34639685153848
  16. -1.21816857996339
  17. -1.0899403083883
  18. -0.961712036813202
  19. -0.833483765238109
  20. -0.705255493663015
  21. -0.577027222087922
  22. -0.448798950512828
  23. -0.320570678937734
  24. -0.192342407362641
  25. -0.064114135787547
  26. 0.0641141357875465
  27. 0.19234240736264
  28. 0.320570678937734
  29. 0.448798950512828
  30. 0.577027222087921
  31. 0.705255493663015
  32. 0.833483765238108
  33. 0.961712036813202
  34. 1.0899403083883
  35. 1.21816857996339
  36. 1.34639685153848
  37. 1.47462512311358
  38. 1.60285339468867
  39. 1.73108166626376
  40. 1.85930993783886
  41. 1.98753820941395
  42. 2.11576648098904
  43. 2.24399475256414
  44. 2.37222302413923
  45. 2.50045129571433
  46. 2.62867956728942
  47. 2.75690783886451
  48. 2.88513611043961
  49. 3.0133643820147
  50. 3.14159265358979

我们现在将创建一些更复杂的图。该contour()函数产生一个以表示三维数据;它就像一张地形图。它需要三个参数:

  • x值的向量(第一维),
  • y值的向量(第二维),
  • 以及一个矩阵,其元素对应z于每对 ( x, y) 坐标的值(第三维)。

与plot()函数一样,还有许多其他输入可用于微调contour()函数的输出。要了解有关这些的更多信息,请通过键入查看帮助文件?contour。

y <- x
f <- outer(x, y, function(x, y) cos(y) / (1 + x^2))
contour(x, y, f)
contour(x, y, f, nlevels = 45, add = T)

在这里插入图片描述

fa <- (f - t(f)) / 2
contour(x, y, fa, nlevels = 15)

在这里插入图片描述


image()函数的工作方式与 相同contour(),不同之处在于它生成一个颜色编码的图,其颜色取决于z值。有时用于在天气预报中绘制温度。或者,persp()可用于生成三维图。参数theta和phi控制查看绘图的角度。

image(x, y, fa)

在这里插入图片描述

persp(x, y, fa)

在这里插入图片描述

persp(x, y, fa, theta = 30)

在这里插入图片描述

persp(x, y, fa, theta = 30, phi = 20)

在这里插入图片描述

1.3数据索引

A <- matrix(1:16, 4, 4)
A
A matrix: 4 × 4 of type int
15 913
261014
371115
481216
A[2, 3]

10

将选择第二行第三列对应的元素。开括号符号后的第一个数字[始终表示行,第二个数字始终表示列。通过提供向量作为索引,我们还可以一次选择多行和多列。

A[c(1, 3), c(2, 4)]
A matrix: 2 × 2 of type int
513
715
A[1:3, 2:4]
A matrix: 3 × 3 of type int
5 913
61014
71115
A[1:2, ]
A matrix: 2 × 4 of type int
15 913
261014
A[, 1:2]
A matrix: 4 × 2 of type int
15
26
37
48

在索引中使用负号,表示保留除索引中指示的行或列之外的所有行或列。

A[-c(1, 3), ]
A matrix: 2 × 4 of type int
261014
481216

1.4 数据导入

对于大多数分析,第一步将数据集导入R. read.table()函数是执行此操作的主要方法之一。帮助文件包含有关如何使用此功能的详细信息。我们可以使用该函数write.table()导出数据。

在尝试加载数据集之前,我们必须确保R知道在正确的目录中搜索数据。例如,在 Windows 系统上,可以使用菜单Change dir …下的选项选择目录File。但是,如何执行此操作的详细信息取决于所使用的操作系统(例如 Windows、Mac、Unix),因此我们在此不提供更多详细信息。

我们首先加载Auto数据集。该数据是ISLR2库的一部分,在第 3 章中讨论过。为了说明该read.table()功能,我们现在从一个文本文件 加载它Auto.data,您可以在教科书网站上找到该文件。下面的命令会将Auto.data文件加载到R一个名为 的对象中,并将其存储为一个名为Auto. 加载数据后,View()可以使用该函数在类似电子表格的窗口中查看数据。(此功能有时可能有点挑剔。如果您在使用它时遇到问题,请尝试使用该head()功能。) 该head()功能还可用于查看数据的前几行。

Auto <- read.table("C:\\Users\\DELL\\Desktop\\Statistic learning\\ISLR\\ALL+CSV+FILES+-+2nd+Edition+-+corrected\\ALL CSV FILES - 2nd Edition\\Auto.data")
View(Auto)
head(Auto)
A data.frame: 398 × 9
V1V2V3V4V5V6V7V8V9
<chr><chr><chr><chr><chr><chr><chr><chr><chr>
mpg cylindersdisplacementhorsepowerweightaccelerationyearoriginname
18.08 307.0 130.0 3504. 12.0 70 1 chevrolet chevelle malibu
15.08 350.0 165.0 3693. 11.5 70 1 buick skylark 320
18.08 318.0 150.0 3436. 11.0 70 1 plymouth satellite
16.08 304.0 150.0 3433. 12.0 70 1 amc rebel sst
17.08 302.0 140.0 3449. 10.5 70 1 ford torino
15.08 429.0 198.0 4341. 10.0 70 1 ford galaxie 500
14.08 454.0 220.0 4354. 9.0 70 1 chevrolet impala
14.08 440.0 215.0 4312. 8.5 70 1 plymouth fury iii
14.08 455.0 225.0 4425. 10.0 70 1 pontiac catalina
15.08 390.0 190.0 3850. 8.5 70 1 amc ambassador dpl
15.08 383.0 170.0 3563. 10.0 70 1 dodge challenger se
14.08 340.0 160.0 3609. 8.0 70 1 plymouth 'cuda 340
15.08 400.0 150.0 3761. 9.5 70 1 chevrolet monte carlo
14.08 455.0 225.0 3086. 10.0 70 1 buick estate wagon (sw)
24.04 113.0 95.00 2372. 15.0 70 3 toyota corona mark ii
22.06 198.0 95.00 2833. 15.5 70 1 plymouth duster
18.06 199.0 97.00 2774. 15.5 70 1 amc hornet
21.06 200.0 85.00 2587. 16.0 70 1 ford maverick
27.04 97.00 88.00 2130. 14.5 70 3 datsun pl510
26.04 97.00 46.00 1835. 20.5 70 2 volkswagen 1131 deluxe sedan
25.04 110.0 87.00 2672. 17.5 70 2 peugeot 504
24.04 107.0 90.00 2430. 14.5 70 2 audi 100 ls
25.04 104.0 95.00 2375. 17.5 70 2 saab 99e
26.04 121.0 113.0 2234. 12.5 70 2 bmw 2002
21.06 199.0 90.00 2648. 15.0 70 1 amc gremlin
10.08 360.0 215.0 4615. 14.0 70 1 ford f250
10.08 307.0 200.0 4376. 15.0 70 1 chevy c20
11.08 318.0 210.0 4382. 13.5 70 1 dodge d200
9.0 8 304.0 193.0 4732. 18.5 70 1 hi 1200d
...........................
28.04112.088.002605.19.6821chevrolet cavalier
27.04112.088.002640.18.6821chevrolet cavalier wagon
34.04112.088.002395.18.0821chevrolet cavalier 2-door
31.04112.085.002575.16.2821pontiac j2000 se hatchback
29.04135.084.002525.16.0821dodge aries se
27.04151.090.002735.18.0821pontiac phoenix
24.04140.092.002865.16.4821ford fairmont futura
36.04105.074.001980.15.3822volkswagen rabbit l
37.0491.0068.002025.18.2823mazda glc custom l
31.0491.0068.001970.17.6823mazda glc custom
38.04105.063.002125.14.7821plymouth horizon miser
36.0498.0070.002125.17.3821mercury lynx l
36.04120.088.002160.14.5823nissan stanza xe
36.04107.075.002205.14.5823honda accord
34.04108.070.002245 16.9823toyota corolla
38.0491.0067.001965.15.0823honda civic
32.0491.0067.001965.15.7823honda civic (auto)
38.0491.0067.001995.16.2823datsun 310 gx
25.06181.0110.02945.16.4821buick century limited
38.06262.085.003015.17.0821oldsmobile cutlass ciera (diesel)
26.04156.092.002585.14.5821chrysler lebaron medallion
22.06232.0112.02835 14.7821ford granada l
32.04144.096.002665.13.9823toyota celica gt
36.04135.084.002370.13.0821dodge charger 2.2
27.04151.090.002950.17.3821chevrolet camaro
27.04140.086.002790.15.6821ford mustang gl
44.0497.0052.002130.24.6822vw pickup
32.04135.084.002295.11.6821dodge rampage
28.04120.079.002625.18.6821ford ranger
31.04119.082.002720.19.4821chevy s-10
A data.frame: 6 × 9
V1V2V3V4V5V6V7V8V9
<chr><chr><chr><chr><chr><chr><chr><chr><chr>
1mpg cylindersdisplacementhorsepowerweightaccelerationyearoriginname
218.08 307.0 130.0 3504. 12.0 70 1 chevrolet chevelle malibu
315.08 350.0 165.0 3693. 11.5 70 1 buick skylark 320
418.08 318.0 150.0 3436. 11.0 70 1 plymouth satellite
516.08 304.0 150.0 3433. 12.0 70 1 amc rebel sst
617.08 302.0 140.0 3449. 10.5 70 1 ford torino

此特定数据集未正确加载,因为R已假定变量名称是数据的一部分,因此已将它们包含在第一行中。数据集还包括许多缺失的观察值,用问号 表示?。缺失值在真实数据集中很常见。使用选项header = T(或header = TRUE在)read.table()函数告知R该文件的第一行包含变量名称,并使用选项na.strings告诉R任何时候它看到一个特定的字符或字符集(如问号)的,它应该是被视为数据矩阵的缺失元

该stringsAsFactors = T参数告诉我们R,任何包含字符串的变量都应被解释为定性变量,并且每个不同的字符串代表该定性变量的不同级别。从 Excel 加载数据的一种简单方法R是将其保存为 csv(逗号分隔值)文件,然后使用该read.csv()函数。

Auto <- read.table("C:\\Users\\DELL\\Desktop\\Statistic learning\\ISLR\\ALL+CSV+FILES+-+2nd+Edition+-+corrected\\ALL CSV FILES - 2nd Edition\\Auto.data",header = T, na.strings = "?", stringsAsFactors = T)
View(Auto)
A data.frame: 397 × 9
mpgcylindersdisplacementhorsepowerweightaccelerationyearoriginname
<dbl><int><dbl><dbl><dbl><dbl><int><int><fct>
188307130350412.0701chevrolet chevelle malibu
158350165369311.5701buick skylark 320
188318150343611.0701plymouth satellite
168304150343312.0701amc rebel sst
178302140344910.5701ford torino
158429198434110.0701ford galaxie 500
1484542204354 9.0701chevrolet impala
1484402154312 8.5701plymouth fury iii
148455225442510.0701pontiac catalina
1583901903850 8.5701amc ambassador dpl
158383170356310.0701dodge challenger se
1483401603609 8.0701plymouth 'cuda 340
1584001503761 9.5701chevrolet monte carlo
148455225308610.0701buick estate wagon (sw)
244113 95237215.0703toyota corona mark ii
226198 95283315.5701plymouth duster
186199 97277415.5701amc hornet
216200 85258716.0701ford maverick
274 97 88213014.5703datsun pl510
264 97 46183520.5702volkswagen 1131 deluxe sedan
254110 87267217.5702peugeot 504
244107 90243014.5702audi 100 ls
254104 95237517.5702saab 99e
264121113223412.5702bmw 2002
216199 90264815.0701amc gremlin
108360215461514.0701ford f250
108307200437615.0701chevy c20
118318210438213.5701dodge d200
98304193473218.5701hi 1200d
274 97 88213014.5713datsun pl510
...........................
284112 88260519.6821chevrolet cavalier
274112 88264018.6821chevrolet cavalier wagon
344112 88239518.0821chevrolet cavalier 2-door
314112 85257516.2821pontiac j2000 se hatchback
294135 84252516.0821dodge aries se
274151 90273518.0821pontiac phoenix
244140 92286516.4821ford fairmont futura
364105 74198015.3822volkswagen rabbit l
374 91 68202518.2823mazda glc custom l
314 91 68197017.6823mazda glc custom
384105 63212514.7821plymouth horizon miser
364 98 70212517.3821mercury lynx l
364120 88216014.5823nissan stanza xe
364107 75220514.5823honda accord
344108 70224516.9823toyota corolla
384 91 67196515.0823honda civic
324 91 67196515.7823honda civic (auto)
384 91 67199516.2823datsun 310 gx
256181110294516.4821buick century limited
386262 85301517.0821oldsmobile cutlass ciera (diesel)
264156 92258514.5821chrysler lebaron medallion
226232112283514.7821ford granada l
324144 96266513.9823toyota celica gt
364135 84237013.0821dodge charger 2.2
274151 90295017.3821chevrolet camaro
274140 86279015.6821ford mustang gl
444 97 52213024.6822vw pickup
324135 84229511.6821dodge rampage
284120 79262518.6821ford ranger
314119 82272019.4821chevy s-10
Auto[1:4, ]
A data.frame: 4 × 9
mpgcylindersdisplacementhorsepowerweightaccelerationyearoriginname
<dbl><int><dbl><dbl><dbl><dbl><int><int><fct>
1188307130350412.0701chevrolet chevelle malibu
2158350165369311.5701buick skylark 320
3188318150343611.0701plymouth satellite
4168304150343312.0701amc rebel sst
dim(Auto)
  1. 397
  2. 9

该dim()函数告诉我们数据有397观察值或行,以及九个变量或列。有多种方法可以处理丢失的数据。在这种情况下,只有五行包含缺失的观察,因此我们选择使用该na.omit()函数来简单地删除这些行。

Auto <- na.omit(Auto)
dim(Auto)
  1. 392
  2. 9
names(Auto)
  1. 'mpg'
  2. 'cylinders'
  3. 'displacement'
  4. 'horsepower'
  5. 'weight'
  6. 'acceleration'
  7. 'year'
  8. 'origin'
  9. 'name'

1.5 绘图和摘要

plot(Auto$cylinders, Auto$mpg)

在这里插入图片描述

attach(Auto)
cylinders <- as.factor(cylinders)
plot(cylinders, mpg)

在这里插入图片描述

plot(cylinders, mpg, col = "red")

在这里插入图片描述

plot(cylinders, mpg, col = "red", varwidth = T,
    horizontal = T)

在这里插入图片描述

plot(cylinders, mpg, col = "red", varwidth = T,
    xlab = "cylinders", ylab = "MPG")

在这里插入图片描述

hist(mpg)

在这里插入图片描述

hist(mpg, col = 2, breaks = 15)

在这里插入图片描述

pairs()函数创建一个散点图矩阵,即每对变量的散点图。我们还可以为变量的一个子集生成散点图。

pairs(Auto)

在这里插入图片描述

pairs(
    ~ mpg + displacement + horsepower + weight + acceleration,
    data = Auto
  )

在这里插入图片描述

与该plot()函数结合使用,identify()提供了一种有用的交互方法,用于识别图上点的特定变量的值。
我们将三个参数传递给identify():X-axis 变量, 是-axis 变量,以及我们希望为每个点打印其值的变量。然后单击图中的一个或多个点并按 Escape 将R打印出感兴趣的变量的值。
在identify()函数下打印的数字对应于所选点的行。

plot(horsepower, mpg)
identify(horsepower, mpg, name)

在这里插入图片描述

plot(horsepower, mpg)

在这里插入图片描述

summary(Auto)
      mpg          cylinders      displacement     horsepower        weight    
 Min.   : 9.00   Min.   :3.000   Min.   : 68.0   Min.   : 46.0   Min.   :1613  
 1st Qu.:17.00   1st Qu.:4.000   1st Qu.:105.0   1st Qu.: 75.0   1st Qu.:2225  
 Median :22.75   Median :4.000   Median :151.0   Median : 93.5   Median :2804  
 Mean   :23.45   Mean   :5.472   Mean   :194.4   Mean   :104.5   Mean   :2978  
 3rd Qu.:29.00   3rd Qu.:8.000   3rd Qu.:275.8   3rd Qu.:126.0   3rd Qu.:3615  
 Max.   :46.60   Max.   :8.000   Max.   :455.0   Max.   :230.0   Max.   :5140  
                                                                               
  acceleration        year           origin                      name    
 Min.   : 8.00   Min.   :70.00   Min.   :1.000   amc matador       :  5  
 1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000   ford pinto        :  5  
 Median :15.50   Median :76.00   Median :1.000   toyota corolla    :  5  
 Mean   :15.54   Mean   :75.98   Mean   :1.577   amc gremlin       :  4  
 3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000   amc hornet        :  4  
 Max.   :24.80   Max.   :82.00   Max.   :3.000   chevrolet chevette:  4  
                                                 (Other)           :365  
summary(mpg)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   9.00   17.00   22.75   23.45   29.00   46.60 
posted @ 2022-08-27 11:09  JOJO数据科学  阅读(231)  评论(0编辑  收藏  举报