R 简明教程

R - Quick Guide

R - Overview

R 是一种编程语言和软件环境,用于统计分析、图形表示和报告。R 由新西兰奥克兰大学的罗斯·伊哈卡和罗伯特·詹特尔曼创建,目前由 R 核心开发团队开发。

R 的核心是一种解释型计算机语言,它允许分支和循环,以及使用函数进行模块化编程。R 允许与 C、C++、.Net、Python 或 FORTRAN 语言编写的过程集成以提高效率。

R 可以根据 GNU 通用公共许可证免费使用,并且为各种操作系统(例如 Linux、Windows 和 Mac)提供了预编译的二进制版本。

R 是根据 GNU 风格的 copy left 分发的免费软件,并且是 GNU 项目的官方部分,称为 GNU S

Evolution of R

R 最初是由奥克兰大学新西兰奥克兰的统计学系 Ross IhakaRobert Gentleman 编写。R 最初出现在 1993 年。

  1. 一大群人通过发送代码和错误报告为 R 做出了贡献。

  2. 自 1997 年年中以来,有一个核心小组(“R 核心团队”)可以修改 R 源代码存档。

Features of R

如前所述,R 是一种编程语言和软件环境,用于统计分析、图形表示和报告。以下是 R 的重要特性−

  1. R 是一种开发完善、简单而有效的编程语言,包括条件、循环、用户定义的递归函数以及输入和输出功能。

  2. R 具有有效的数据处理和存储设施,

  3. R 提供了一套用于计算数组、列表、向量和矩阵的运算符。

  4. R 提供了一大套用于数据分析的、连贯和集成的工具。

  5. R 提供了用于数据分析和显示的图形功能,可以直接在计算机上显示或打印在纸张上。

总而言之,R 是世界上使用最广泛的统计编程语言。它是数据科学家的头号选择,并且得到一群充满活力和才华的贡献者的支持。R 在大学中教授,并在关键任务业务应用程序中部署。本教程将通过简单且容易的步骤教您 R 编程以及合适的示例。

R - Environment Setup

Local Environment Setup

如果您仍希望为 R 设置环境,可以按照以下步骤操作。

Windows Installation

您可以从 R-3.2.2 for Windows (32/64 bit) 下载 R 的 Windows 安装程序版本并将其保存在本地目录中。

因为它是一个带有名称“R-version-win.exe”的 Windows 安装程序(.exe)。您可以双击并运行安装程序,接受默认设置。如果您的 Windows 是 32 位版本,它将安装 32 位版本。但如果您的 Windows 是 64 位版本,那么它将安装 32 位和 64 位版本。

安装后,您可以在 Windows 程序文件下的目录结构“R\R3.2.2\bin\i386\Rgui.exe”中找到运行该程序的图标。单击此图标将显示 R-GUI,它是用于进行 R 编程的 R 控制台。

Linux Installation

R 的二进制文件适用于许多版本的 Linux,具体地址为 R Binaries

安装 Linux 的说明因版本不同而不同。这些步骤在所述链接的每种 Linux 版本下都有提及。但是,如果您很着急,那么您可以使用 yum 命令安装 R,如下所示 −

$ yum install R

上述命令将安装 R 编程的核心功能以及标准包,如果您仍然需要其他包,则可以启动 R 提示,如下所示 −

$ R
R version 3.2.0 (2015-04-16) -- "Full of  Ingredients"
Copyright (C) 2015 The R Foundation for Statistical Computing
Platform: x86_64-redhat-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many  contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
>

现在,您可以使用 R 提示下的 install 命令安装所需的包。例如,以下命令将安装用于 3D 图表的 plotrix 包。

> install.packages("plotrix")

R - Basic Syntax

按照惯例,我们将通过编写“Hello, World!”程序开始学习 R 编程。根据需要,您可以在 R 命令提示符处编程,也可以使用 R 脚本文件编写程序。让我们一一检查。

R Command Prompt

一旦你设置好了 R 环境,那么只需在命令提示符下键入以下命令即可轻松启动 R 命令提示符:

$ R

这将启动 R 解释器,你将得到一个提示符 >,可以在此开始键入你的程序,如下所示:

> myString <- "Hello, World!"
> print ( myString)
[1] "Hello, World!"

这里的第一条语句定义了一个字符串变量 myString,我们在其中分配了一个字符串 "Hello,World!",然后下一条语句 print() 用于打印存储在变量 myString 中的值。

R Script File

通常,你将通过编写脚本文件来进行编程,然后利用称为 Rscript 的 R 解释器在命令提示符下执行这些脚本。因此,让我们开始在名为 test.R 的文本文件中编写以下代码:

# My first program in R Programming
myString <- "Hello, World!"

print ( myString)

将以上代码保存在文件 test.R 中,并在 Linux 命令提示符下执行,如下所示。即使你使用的是 Windows 或其他系统,语法仍保持不变。

$ Rscript test.R

当我们运行以上程序时,它会生成以下结果。

[1] "Hello, World!"

Comments

注释就像 R 程序中的帮助文字,它们在执行实际程序时会被解释器忽略。单行注释在语句的开头使用 # 编写,如下所示:

# My first program in R Programming

R 不支持多行注释,但你可以执行类似以下内容的技巧:

if(FALSE) {
   "This is a demo for multi-line comments and it should be put inside either a
      single OR double quote"
}

myString <- "Hello, World!"
print ( myString)
[1] "Hello, World!"

尽管以上注释将由 R 解释器执行,但它们不会干扰你的实际程序。你应该将此类注释放在单引号或双引号内。

R - Data Types

通常,在任何编程语言中进行编程时,你需要使用各种变量来存储各种信息。变量只不过是用于存储值的保留内存位置。这意味着,当你创建变量时,你会在内存中保留一些空间。

你可能希望存储各种数据类型的信息,如字符、宽字符、整数、浮点数、双浮点数、布尔值等。根据变量的数据类型,操作系统分配内存,并决定在保留内存中可以存储什么。

与其他编程语言(如 C 和 Java)不同,在 R 中,变量不会被声明为某种数据类型。这些变量会被分配 R 对象并且 R 对象的数据类型会成为变量的数据类型。有很多类型的 R 对象。经常使用的是 −

  1. Vectors

  2. Lists

  3. Matrices

  4. Arrays

  5. Factors

  6. Data Frames

这些对象中最简单的是 vector object 并且这些原子向量的有六个数据类型,也被称为向量的六个类别。其他 R 对象建立在原子向量之上。

Data Type

Example

Verify

Logical

TRUE, FALSE

Live Demo v ← TRUEprint(class(v))它产生以下结果 −[1] "logical"

Numeric

12.3, 5, 999

Live Demo v ← 23.5print(class(v))它产生以下结果 −[1] "numeric"

Integer

2L, 34L, 0L

Live Demo v ← 2Lprint(class(v))它产生以下结果 −[1] "integer"

Complex

3 + 2i

Live Demo v ← 2+5iprint(class(v))它产生以下结果 −[1] "complex"

Character

'a' , '"good", "TRUE", '23.4'

Live Demo v ← "TRUE"print(class(v))它产生以下结果 −[1] "character"

Raw

"Hello" 存储为 48 65 6c 6c 6f

Live Demo v ← charToRaw("Hello")print(class(v))它生成以下结果 −[1] "raw"

在 R 编程中,最基本的数据类型是 R 对象,称为 vectors ,它持有不同类别的元素,如上所示。请注意,在 R 中,类别的数量不限于上述六种类型。例如,我们可以使用许多原子向量并创建类为数组的数组。

Vectors

当您希望创建包含多个元素的向量时,您应该使用 c() 函数,它表示将元素组合成一个向量。

# Create a vector.
apple <- c('red','green',"yellow")
print(apple)

# Get the class of the vector.
print(class(apple))

当我们执行上述代码时,会产生以下结果 -

[1] "red"    "green"  "yellow"
[1] "character"

Lists

列表是 R 对象,它可以在内部包含许多不同类型的元素,例如向量、函数,甚至另一个列表。

# Create a list.
list1 <- list(c(2,5,3),21.3,sin)

# Print the list.
print(list1)

当我们执行上述代码时,会产生以下结果 -

[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x)  .Primitive("sin")

Matrices

矩阵是二维矩形数据集。它可以用一个向量输入到矩阵函数中来创建。

# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)

当我们执行上述代码时,会产生以下结果 -

     [,1] [,2] [,3]
[1,] "a"  "a"  "b"
[2,] "c"  "b"  "a"

Arrays

当矩阵限制在两个维度时,数组可以是任何数量的维度。数组函数采用 dim 属性,它创建所需数量的维度。在下面的示例中,我们创建了一个数组,其中有两个元素,每个元素都是 3x3 矩阵。

# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)

当我们执行上述代码时,会产生以下结果 -

, , 1

     [,1]     [,2]     [,3]
[1,] "green"  "yellow" "green"
[2,] "yellow" "green"  "yellow"
[3,] "green"  "yellow" "green"

, , 2

     [,1]     [,2]     [,3]
[1,] "yellow" "green"  "yellow"
[2,] "green"  "yellow" "green"
[3,] "yellow" "green"  "yellow"

Factors

因子是使用向量创建的 r 对象。它存储向量以及元素在向量中的离散值,作为标签。标签总是字符,而不管输入向量中是数字、字符还是布尔等。它们在统计建模中很有用。

使用 factor() 函数创建因子。 nlevels 函数给出级别计数。

# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')

# Create a factor object.
factor_apple <- factor(apple_colors)

# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))

当我们执行上述代码时,会产生以下结果 -

[1] green  green  yellow red    red    red    green
Levels: green red yellow
[1] 3

Data Frames

数据框是表格数据对象。与数据框中的矩阵不同,每列可以包含不同模式的数据。第一列可以是数字,而第二列可以是字符,第三列可以是逻辑。它是一个长度相等的向量的列表。

使用 data.frame() 函数创建数据框。

# Create the data frame.
BMI <- 	data.frame(
   gender = c("Male", "Male","Female"),
   height = c(152, 171.5, 165),
   weight = c(81,93, 78),
   Age = c(42,38,26)
)
print(BMI)

当我们执行上述代码时,会产生以下结果 -

  gender height weight Age
1   Male  152.0     81  42
2   Male  171.5     93  38
3 Female  165.0     78  26

R - Variables

变量为我们提供命名的存储,我们的程序可以操作这些存储。R 中的变量可以存储一个原子向量、一组原子向量或许多 Robjects 的组合。有效的变量名称由字母、数字和点或下划线字符组成。变量名称以字母或点开头,后面不跟数字。

Variable Name

Validity

Reason

var_name2.

valid

有字母、数字、点和下划线

var_name%

Invalid

有字符“%”。只允许点(.)和下划线。

2var_name

invalid

Starts with a number

.var_name, var.name

valid

可以以点(.)开头,但点(.)后面不能跟数字。

.2var_name

invalid

开头点后面跟数字,使其无效。

_var_name

invalid

以 _ 开头,它是不合法的

Variable Assignment

可以使用向左、向右和等于运算符为变量分配值。可以使用 print()cat() 函数打印变量的值。 cat() 函数将多个项目合并为一个连续的打印输出。

# Assignment using equal operator.
var.1 = c(0,1,2,3)

# Assignment using leftward operator.
var.2 <- c("learn","R")

# Assignment using rightward operator.
c(TRUE,1) -> var.3

print(var.1)
cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")

当我们执行上述代码时,会产生以下结果 -

[1] 0 1 2 3
var.1 is  0 1 2 3
var.2 is  learn R
var.3 is  1 1

Note − 向量 c(TRUE,1) 混合了逻辑和数字类型。所以逻辑类型被强制转换为数字类型,其中 TRUE 为 1。

Data Type of a Variable

在 R 中,一个变量本身没有声明任何数据类型,而是获取分配给它的 R 对象的数据类型。因此 R 被称为动态类型语言,这意味着我们可以在程序中反复更改同一变量的数据类型。

var_x <- "Hello"
cat("The class of var_x is ",class(var_x),"\n")

var_x <- 34.5
cat("  Now the class of var_x is ",class(var_x),"\n")

var_x <- 27L
cat("   Next the class of var_x becomes ",class(var_x),"\n")

当我们执行上述代码时,会产生以下结果 -

The class of var_x is  character
   Now the class of var_x is  numeric
      Next the class of var_x becomes  integer

Finding Variables

要了解当前在工作空间中可用的所有变量,我们使用 ls() 函数。ls() 函数还可以使用模式来匹配变量名称。

print(ls())

当我们执行上述代码时,会产生以下结果 -

[1] "my var"     "my_new_var" "my_var"     "var.1"
[5] "var.2"      "var.3"      "var.name"   "var_name2."
[9] "var_x"      "varname"

Note − 它是取决于在您的环境中声明哪些变量的一个示例输出。

ls() 函数可以使用模式来匹配变量名称。

# List the variables starting with the pattern "var".
print(ls(pattern = "var"))

当我们执行上述代码时,会产生以下结果 -

[1] "my var"     "my_new_var" "my_var"     "var.1"
[5] "var.2"      "var.3"      "var.name"   "var_name2."
[9] "var_x"      "varname"

dot(.) 开头的变量被隐藏,可以使用 ls() 函数的 "all.names = TRUE" 参数来列出它们。

print(ls(all.name = TRUE))

当我们执行上述代码时,会产生以下结果 -

[1] ".cars"        ".Random.seed" ".var_name"    ".varname"     ".varname2"
[6] "my var"       "my_new_var"   "my_var"       "var.1"        "var.2"
[11]"var.3"        "var.name"     "var_name2."   "var_x"

Deleting Variables

可以使用 rm() 函数删除变量。下面我们删除变量 var.3。在打印变量的值时会抛出错误。

rm(var.3)
print(var.3)

当我们执行上述代码时,会产生以下结果 -

[1] "var.3"
Error in print(var.3) : object 'var.3' not found

可以使用 rm()ls() 函数一起删除所有变量。

rm(list = ls())
print(ls())

当我们执行上述代码时,会产生以下结果 -

character(0)

R - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators.

Types of Operators

We have the following types of operators in R programming −

  1. Arithmetic Operators

  2. Relational Operators

  3. Logical Operators

  4. Assignment Operators

  5. Miscellaneous Operators

Arithmetic Operators

Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector.

Operator

Description

Example

+

Adds two vectors

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v+t) it produces the following result − [1] 10.0 8.5 10.0

Subtracts second vector from the first

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v-t) it produces the following result − [1] -6.0 2.5 2.0

*

Multiplies both vectors

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v*t) it produces the following result − [1] 16.0 16.5 24.0

/

Divide the first vector with the second

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v/t) When we execute the above code, it produces the following result − [1] 0.250000 1.833333 1.500000

%%

Give the remainder of the first vector with the second

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v%%t) it produces the following result − [1] 2.0 2.5 2.0

%/%

The result of division of first vector with second (quotient)

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v%/%t) it produces the following result − [1] 0 1 1

^

The first vector raised to the exponent of second vector

Live Demov ← c( 2,5.5,6) t ← c(8, 3, 4) print(v^t) it produces the following result − [1] 256.000 166.375 1296.000

Relational Operators

Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.

Operator

Description

Example

>

Checks if each element of the first vector is greater than the corresponding element of the second vector.

Live Demov ← c(2,5.5,6,9) t ← c(8,2.5,14,9) print(v>t) it produces the following result − [1] FALSE TRUE FALSE FALSE

<

Checks if each element of the first vector is less than the corresponding element of the second vector.

Live Demov ← c(2,5.5,6,9) t ← c(8,2.5,14,9) print(v < t) it produces the following result − [1] TRUE FALSE TRUE FALSE

==

Checks if each element of the first vector is equal to the corresponding element of the second vector.

Live Demov ← c(2,5.5,6,9) t ← c(8,2.5,14,9) print(v == t) it produces the following result − [1] FALSE FALSE FALSE TRUE

Checks if each element of the first vector is less than or equal to the corresponding element of the second vector.

Live Demov ← c(2,5.5,6,9) t ← c(8,2.5,14,9) print(v⇐t) it produces the following result − [1] TRUE FALSE TRUE TRUE

>=

Checks if each element of the first vector is greater than or equal to the corresponding element of the second vector.

Live Demov ← c(2,5.5,6,9) t ← c(8,2.5,14,9) print(v>=t) it produces the following result − [1] FALSE TRUE FALSE TRUE

!=

Checks if each element of the first vector is unequal to the corresponding element of the second vector.

Live Demov ← c(2,5.5,6,9) t ← c(8,2.5,14,9) print(v!=t) it produces the following result − [1] TRUE TRUE TRUE FALSE

Logical Operators

下表显示了 R 语言支持的逻辑运算符。它仅适用于逻辑、数值或复杂类型的向量。大于 1 的所有数字都被视为逻辑值 TRUE。

第一个向量的每个元素都与第二个向量的对应元素进行比较。比较的结果是布尔值。

Operator

Description

Example

&

它称为元素级逻辑 AND 运算符。它将第一个向量的每个元素与第二个向量的对应元素组合在一起,如果两个元素都是 TRUE,则给出一个输出 TRUE。

Live Demo v ← c(3,1,TRUE,2+3i)t ← c(4,1,FALSE,2+3i)print(v&t)产生以下结果 −[1] TRUE TRUE FALSE TRUE

它称为元素级逻辑 OR 运算符。它将第一个向量的每个元素与第二个向量的对应元素组合在一起,如果其中一个元素是 TRUE,则给出一个输出 TRUE。

Live Demo v ← c(3,0,TRUE,2+2i)t ← c(4,0,FALSE,2+3i)print(v

t)产生以下结果 −[1] TRUE FALSE TRUE TRUE

!

逻辑运算符 && 和 || 仅考虑向量的第一个元素,并给出一个单元素向量的输出。

Operator

Description

Example

&&

称为逻辑 AND 运算符。获取两个向量的第一个元素,并且仅当两者都为 TRUE 时才给 TRUE。

Live Demo v ← c(3,0,TRUE,2+2i)t ← c(1,3,TRUE,2+3i)print(v&&t)产生以下结果 −[1] TRUE

称为逻辑 OR 运算符。获取两个向量的第一个元素,并且如果其中一个为 TRUE,则给 TRUE。

Live Demo v ← c(0,0,TRUE,2+2i)t ← c(0,3,TRUE,2+3i)print(v

Assignment Operators

这些运算符用于为向量分配值。

Operator

Description

Example

<− or = or <<−

Called Left Assignment

Live Demo v1 ← c(3,1,TRUE,2+3i)v2 <← c(3,1,TRUE,2+3i)v3 = c(3,1,TRUE,2+3i)print(v1)print(v2)print(v3)产生以下结果 −[1] 3+0i 1+0i 1+0i 2+3i[1] 3+0i 1+0i 1+0i 2+3i[1] 3+0i 1+0i 1+0i 2+3i

→ or →>

Called Right Assignment

Live Demo c(3,1,TRUE,2+3i) → v1c(3,1,TRUE,2+3i) →> v2print(v1)print(v2)产生以下结果 −[1] 3+0i 1+0i 1+0i 2+3i[1] 3+0i 1+0i 1+0i 2+3i

Miscellaneous Operators

这些运算符用于特殊目的,而不是常规的数学或逻辑运算。

Operator

Description

Example

:

冒号运算符。它为向量按顺序创建一系列数字。

Live Demo v ← 2:8print(v)产生以下结果 −[1] 2 3 4 5 6 7 8

%in%

此运算符用于识别元素是否属于向量。

Live Demo v1 ← 8v2 ← 12t ← 1:10print(v1 %in% t)print(v2 %in% t)产生以下结果 −[1] TRUE[1] FALSE

%*%

此运算符用于用矩阵与其转置相乘。

Live Demo M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)t = M %*% t(M)print(t)产生以下结果 − [,1] [,2][1,] 65 82[2,] 82 117

R - Decision making

决策结构要求程序员指定程序要评估或测试的一个或多个条件,以及在确定条件为 true 时要执行的语句或语句,而且在条件确定为 false 时可能还要执行其他一些语句。

以下是大多数编程语言中常见的典型决策结构的一般形式 −

r decision making

R 提供以下类型的决策语句。单击以下链接查看其详细信息。

Sr.No.

Statement & Description

1

if statement if 语句由一个布尔表达式后面跟着一个或多个语句组成。

2

if…​else statement if 语句后可跟一个可选的 else 语句,该语句在布尔表达式为假时执行。

3

switch statement switch 语句允许针对值列表来测试变量的相等性。

R - Loops

有时可能需要多次执行一个代码块。通常,语句以顺序执行。在一个函数中的第一个语句先执行,然后执行第二个语句,依此类推。

编程语言提供了各种控制结构,允许执行更复杂的路径。

循环语句使我们可以多次执行一个语句或一组语句,以下是在大多数编程语言中循环语句的一般形式 −

loop architecture

R 编程语言提供以下类型的循环来处理循环需要。点击以下链接检查其详细信息。

Sr.No.

Loop Type & Description

1

repeat loop 多次执行一系列语句,并且缩写了管理循环变量的代码。

2

while loop 在一个给定条件为真时重复一个语句或一组语句。它在执行循环主体之前测试条件。

3

for loop 与 while 语句类似,但它在循环体结尾处测试条件。

Loop Control Statements

循环控制语句改变了它在正常序列中的执行。当执行退出一个作用域时,在该作用域中创建的所有自动对象会被销毁。

R 支持以下控制语句。单击以下链接查看其详细信息。

Sr.No.

Control Statement & Description

1

break statement 终止 loop 语句,并将执行转移到循环紧后面的语句。

2

Next statement next 语句模拟 R switch 的行为。

R - Functions

函数是一组陈述,为了执行特定的任务而被组织在一起。R 具有大量的内置函数并且用户可以创建自己的函数。

在 R 中,函数是一个对象,因此 R 解释器能够将控制权传递给函数,连同对于函数完成操作可能必要的参数。

函数执行其任务并将其控制权以及存储在其他对象中的任何结果返回给解释器。

Function Definition

R 函数是通过使用关键字 function 创建的。R 函数定义的基本语法如下−

function_name <- function(arg_1, arg_2, ...) {
   Function body
}

Function Components

函数的不同部分是−

  1. Function Name − 这是函数的实际名称。它作为具有此名称的对象存储在 R 环境中。

  2. Arguments − 参数是占位符。当一个函数被调用时,您将一个值传递给了参数。参数是可选的;也就是说,函数可能没有参数。参数也可以有默认值。

  3. Function Body − 函数主体包含一系列的陈述,定义了函数所做的事情。

  4. Return Value − 函数的返回值是函数主体中要计算的最后一个表达式。

R 有许多 in-built 函数,可在程序中直接调用,而无需先定义它们。我们还可以创建和使用我们自己的函数,称为 user defined 函数。

Built-in Function

内置函数的简单示例包括 seq()mean()max()sum(x)paste(…​) 等。它们由用户编写的程序直接调用。你可以参考 most widely used R functions.

# Create a sequence of numbers from 32 to 44.
print(seq(32,44))

# Find mean of numbers from 25 to 82.
print(mean(25:82))

# Find sum of numbers frm 41 to 68.
print(sum(41:68))

当我们执行上述代码时,会产生以下结果 -

[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526

User-defined Function

我们可以在 R 中创建用户定义函数。它们取决于用户的要求,并且在创建后可以像内置函数一样使用它们。以下是创建和使用函数的一个示例。

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}

Calling a Function

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}

# Call the function new.function supplying 6 as an argument.
new.function(6)

当我们执行上述代码时,会产生以下结果 -

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

Calling a Function without an Argument

# Create a function without an argument.
new.function <- function() {
   for(i in 1:5) {
      print(i^2)
   }
}

# Call the function without supplying an argument.
new.function()

当我们执行上述代码时,会产生以下结果 -

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Calling a Function with Argument Values (by position and by name)

可以按函数中定义的相同顺序提供函数调用的参数,也可以按不同的顺序提供参数,但是被分配给参数的名称。

# Create a function with arguments.
new.function <- function(a,b,c) {
   result <- a * b + c
   print(result)
}

# Call the function by position of arguments.
new.function(5,3,11)

# Call the function by names of the arguments.
new.function(a = 11, b = 5, c = 3)

当我们执行上述代码时,会产生以下结果 -

[1] 26
[1] 58

Calling a Function with Default Argument

我们可以定义函数定义中的参数的值,并且在不提供任何参数的情况下调用函数以获取默认结果。但是,我们也可以通过提供参数的新值并获得非默认结果来调用此类函数。

# Create a function with arguments.
new.function <- function(a = 3, b = 6) {
   result <- a * b
   print(result)
}

# Call the function without giving any argument.
new.function()

# Call the function with giving new values of the argument.
new.function(9,5)

当我们执行上述代码时,会产生以下结果 -

[1] 18
[1] 45

Lazy Evaluation of Function

对函数的参数进行惰性求值,这意味着只有函数体需要时才会评估它们。

# Create a function with arguments.
new.function <- function(a, b) {
   print(a^2)
   print(a)
   print(b)
}

# Evaluate the function without supplying one of the arguments.
new.function(6)

当我们执行上述代码时,会产生以下结果 -

[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default

R - Strings

在 R 中用一对单引号或双引号写的任何值都被视为一个字符串。内部上,R 将每一个字符串都存储在双引号中,即使您用单引号创建它们。

Rules Applied in String Construction

  1. 字符串开头和结尾的引号都应该是双引号或单引号。它们不能混合使用。

  2. 可以将双引号插入到以单引号开始和结尾的字符串中。

  3. 可以将单引号插入到以双引号开始和结尾的字符串中。

  4. 不能将双引号插入到以双引号开始和结尾的字符串中。

  5. 不能将单引号插入到以单引号开始和结尾的字符串中。

Examples of Valid Strings

以下示例说明了在 R 中创建字符串的规则。

a <- 'Start and end with single quote'
print(a)

b <- "Start and end with double quotes"
print(b)

c <- "single quote ' in between double quotes"
print(c)

d <- 'Double quotes " in between single quote'
print(d)

运行以上代码时,我们将得到以下输出 −

[1] "Start and end with single quote"
[1] "Start and end with double quotes"
[1] "single quote ' in between double quote"
[1] "Double quote \" in between single quote"

Examples of Invalid Strings

e <- 'Mixed quotes"
print(e)

f <- 'Single quote ' inside single quote'
print(f)

g <- "Double quotes " inside double quotes"
print(g)

当我们运行脚本时,它失败并给出以下结果。

Error: unexpected symbol in:
"print(e)
f <- 'Single"
Execution halted

String Manipulation

Concatenating Strings - paste() function

R 中使用 paste() 函数组合多个字符串。它可以接受任意数量的参数进行组合。

Syntax

paste 函数的基本语法为:

paste(..., sep = " ", collapse = NULL)

以下是所用参数的描述 -

  1. &#8230;&#8203; 表示组合的任意数量的参数。

  2. sep 表示参数之间的任意分隔符。它是可选的。

  3. collapse 用于消除两个字符串之间的空格。但不是一个字符串的两个单词之间的空格。

Example

a <- "Hello"
b <- 'How'
c <- "are you? "

print(paste(a,b,c))

print(paste(a,b,c, sep = "-"))

print(paste(a,b,c, sep = "", collapse = ""))

当我们执行上述代码时,会产生以下结果 -

[1] "Hello How are you? "
[1] "Hello-How-are you? "
[1] "HelloHoware you? "

Formatting numbers & strings - format() function

可以使用 format() 函数将数字和字符串格式化为特定样式。

Syntax

format 函数的基本语法为:

format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))

以下是所用参数的描述 -

  1. x 是向量的输入。

  2. digits 是显示的数字的总数。

  3. nsmall 是小数点右边最少的数字。

  4. scientific 设置为 TRUE 以显示科学计数法。

  5. width 表示初始填充空格显示的最少宽度。

  6. justify 是将字符串显示在左、右或中间。

Example

# Total number of digits displayed. Last digit rounded off.
result <- format(23.123456789, digits = 9)
print(result)

# Display numbers in scientific notation.
result <- format(c(6, 13.14521), scientific = TRUE)
print(result)

# The minimum number of digits to the right of the decimal point.
result <- format(23.47, nsmall = 5)
print(result)

# Format treats everything as a string.
result <- format(6)
print(result)

# Numbers are padded with blank in the beginning for width.
result <- format(13.7, width = 6)
print(result)

# Left justify strings.
result <- format("Hello", width = 8, justify = "l")
print(result)

# Justfy string with center.
result <- format("Hello", width = 8, justify = "c")
print(result)

当我们执行上述代码时,会产生以下结果 -

[1] "23.1234568"
[1] "6.000000e+00" "1.314521e+01"
[1] "23.47000"
[1] "6"
[1] "  13.7"
[1] "Hello   "
[1] " Hello  "

Counting number of characters in a string - nchar() function

此函数计算字符串中包括空格在内的字符数。

Syntax

nchar() 函数的基本语法为:

nchar(x)

以下是所用参数的描述 -

  1. x 是向量的输入。

Example

result <- nchar("Count the number of characters")
print(result)

当我们执行上述代码时,会产生以下结果 -

[1] 30

Changing the case - toupper() & tolower() functions

这些函数更改字符串的字符的大小写。

Syntax

toupper() 和 tolower() 函数的基本语法为:

toupper(x)
tolower(x)

以下是所用参数的描述 -

  1. x 是向量的输入。

Example

# Changing to Upper case.
result <- toupper("Changing To Upper")
print(result)

# Changing to lower case.
result <- tolower("Changing To Lower")
print(result)

当我们执行上述代码时,会产生以下结果 -

[1] "CHANGING TO UPPER"
[1] "changing to lower"

Extracting parts of a string - substring() function

此函数提取字符串的部分信息。

Syntax

substring() 函数的基本语法为:

substring(x,first,last)

以下是所用参数的描述 -

  1. x 是字符向量输入。

  2. first 是要提取的第一个字符的位置。

  3. last 是要提取的最后一个字符的位置。

Example

# Extract characters from 5th to 7th position.
result <- substring("Extract", 5, 7)
print(result)

当我们执行上述代码时,会产生以下结果 -

[1] "act"

R - Vectors

向量是 R 中最基本的数据对象,有六种类型的基本向量,它们是逻辑型,整数型,双精度浮点型,复数型,字符型和原始型。

Vector Creation

Single Element Vector

即使你在 R 中只写一个值,它也会变成长度为 1 的向量,且属于以上其中一种向量类型。

# Atomic vector of type character.
print("abc");

# Atomic vector of type double.
print(12.5)

# Atomic vector of type integer.
print(63L)

# Atomic vector of type logical.
print(TRUE)

# Atomic vector of type complex.
print(2+3i)

# Atomic vector of type raw.
print(charToRaw('hello'))

当我们执行上述代码时,会产生以下结果 -

[1] "abc"
[1] 12.5
[1] 63
[1] TRUE
[1] 2+3i
[1] 68 65 6c 6c 6f

Multiple Elements Vector

Using colon operator with numeric data

# Creating a sequence from 5 to 13.
v <- 5:13
print(v)

# Creating a sequence from 6.6 to 12.6.
v <- 6.6:12.6
print(v)

# If the final element specified does not belong to the sequence then it is discarded.
v <- 3.8:11.4
print(v)

当我们执行上述代码时,会产生以下结果 -

[1]  5  6  7  8  9 10 11 12 13
[1]  6.6  7.6  8.6  9.6 10.6 11.6 12.6
[1]  3.8  4.8  5.8  6.8  7.8  8.8  9.8 10.8

Using sequence (Seq.) operator

# Create vector with elements from 5 to 9 incrementing by 0.4.
print(seq(5, 9, by = 0.4))

当我们执行上述代码时,会产生以下结果 -

[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0

Using the c() function

如果其中一个元素为字符,则将非字符值强制转换为字符类型。

# The logical and numeric values are converted to characters.
s <- c('apple','red',5,TRUE)
print(s)

当我们执行上述代码时,会产生以下结果 -

[1] "apple" "red"   "5"     "TRUE"

Accessing Vector Elements

向量的元素通过索引进行访问。 [ ] brackets 用于索引。索引从位置 1 开始,在索引中给出一个负值则从此结果中删除该元素。 TRUEFALSE01 也可用于索引。

# Accessing vector elements using position.
t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat")
u <- t[c(2,3,6)]
print(u)

# Accessing vector elements using logical indexing.
v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]
print(v)

# Accessing vector elements using negative indexing.
x <- t[c(-2,-5)]
print(x)

# Accessing vector elements using 0/1 indexing.
y <- t[c(0,0,0,0,0,0,1)]
print(y)

当我们执行上述代码时,会产生以下结果 -

[1] "Mon" "Tue" "Fri"
[1] "Sun" "Fri"
[1] "Sun" "Tue" "Wed" "Fri" "Sat"
[1] "Sun"

Vector Manipulation

Vector arithmetic

两个长度相同的向量可以通过相加、相减、相乘或相除得到一个向量输出结果。

# Create two vectors.
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11,0,8,1,2)

# Vector addition.
add.result <- v1+v2
print(add.result)

# Vector subtraction.
sub.result <- v1-v2
print(sub.result)

# Vector multiplication.
multi.result <- v1*v2
print(multi.result)

# Vector division.
divi.result <- v1/v2
print(divi.result)

当我们执行上述代码时,会产生以下结果 -

[1]  7 19  4 13  1 13
[1] -1 -3  4 -3 -1  9
[1] 12 88  0 40  0 22
[1] 0.7500000 0.7272727       Inf 0.6250000 0.0000000 5.5000000

Vector Element Recycling

如果我们对两个长度不等的向量进行算术运算,则较短向量中的元素会被循环利用以完成运算。

v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11)
# V2 becomes c(4,11,4,11,4,11)

add.result <- v1+v2
print(add.result)

sub.result <- v1-v2
print(sub.result)

当我们执行上述代码时,会产生以下结果 -

[1]  7 19  8 16  4 22
[1] -1 -3  0 -6 -4  0

Vector Element Sorting

向量的元素可以使用 sort() 函数进行排序。

v <- c(3,8,4,5,0,11, -9, 304)

# Sort the elements of the vector.
sort.result <- sort(v)
print(sort.result)

# Sort the elements in the reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)

# Sorting character vectors.
v <- c("Red","Blue","yellow","violet")
sort.result <- sort(v)
print(sort.result)

# Sorting character vectors in reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)

当我们执行上述代码时,会产生以下结果 -

[1]  -9   0   3   4   5   8  11 304
[1] 304  11   8   5   4   3   0  -9
[1] "Blue"   "Red"    "violet" "yellow"
[1] "yellow" "violet" "Red"    "Blue"

R - Lists

列表是一些 R 对象,其中包含不同类型的元素,例如数字、字符串、向量以及一个内部列表。列表还可以包含一个矩阵或一个函数作为其元素。使用 list() 函数创建列表。

Creating a List

以下是一个创建包含字符串、数字、向量和逻辑值列表的示例。

# Create a list containing strings, numbers, vectors and a logical
# values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)

当我们执行上述代码时,会产生以下结果 -

[[1]]
[1] "Red"

[[2]]
[1] "Green"

[[3]]
[1] 21 32 11

[[4]]
[1] TRUE

[[5]]
[1] 51.23

[[6]]
[1] 119.1

Naming List Elements

列表元素可以得到名称,并且我们可以使用这些名称来对其进行访问。

# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
   list("green",12.3))

# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Show the list.
print(list_data)

当我们执行上述代码时,会产生以下结果 -

$`1st_Quarter`
[1] "Jan" "Feb" "Mar"

$A_Matrix
     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8

$A_Inner_list
$A_Inner_list[[1]]
[1] "green"

$A_Inner_list[[2]]
[1] 12.3

Accessing List Elements

可以通过列表中元素的索引来访问该元素。在已命名列表的情况下,还可以使用名称来访问元素。

我们在以上示例中继续使用列表 −

# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
   list("green",12.3))

# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Access the first element of the list.
print(list_data[1])

# Access the thrid element. As it is also a list, all its elements will be printed.
print(list_data[3])

# Access the list element using the name of the element.
print(list_data$A_Matrix)

当我们执行上述代码时,会产生以下结果 -

$`1st_Quarter`
[1] "Jan" "Feb" "Mar"

$A_Inner_list
$A_Inner_list[[1]]
[1] "green"

$A_Inner_list[[2]]
[1] 12.3

     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8

Manipulating List Elements

我们可以添加、删除和更新列表元素,如下所示。我们只能在列表的末尾添加和删除元素。但是我们可以更新任何元素。

# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
   list("green",12.3))

# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Add element at the end of the list.
list_data[4] <- "New element"
print(list_data[4])

# Remove the last element.
list_data[4] <- NULL

# Print the 4th Element.
print(list_data[4])

# Update the 3rd Element.
list_data[3] <- "updated element"
print(list_data[3])

当我们执行上述代码时,会产生以下结果 -

[[1]]
[1] "New element"

$<NA>
NULL

$`A Inner list`
[1] "updated element"

Merging Lists

可以通过将所有列表置于一个 list() 函数中,来合并多个列表成一个列表。

# Create two lists.
list1 <- list(1,2,3)
list2 <- list("Sun","Mon","Tue")

# Merge the two lists.
merged.list <- c(list1,list2)

# Print the merged list.
print(merged.list)

当我们执行上述代码时,会产生以下结果 -

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] "Sun"

[[5]]
[1] "Mon"

[[6]]
[1] "Tue"

Converting List to Vector

可以通过将列表转换为向量的形式,使向量的元素可用于进一步的操作。在将列表转换为向量之后,可以使用所有在向量运算。为了进行这个转换,我们使用 unlist() 函数。这个函数将列表作为输入,并生成一个向量。

# Create lists.
list1 <- list(1:5)
print(list1)

list2 <-list(10:14)
print(list2)

# Convert the lists to vectors.
v1 <- unlist(list1)
v2 <- unlist(list2)

print(v1)
print(v2)

# Now add the vectors
result <- v1+v2
print(result)

当我们执行上述代码时,会产生以下结果 -

[[1]]
[1] 1 2 3 4 5

[[1]]
[1] 10 11 12 13 14

[1] 1 2 3 4 5
[1] 10 11 12 13 14
[1] 11 13 15 17 19

R - Matrices

矩阵是 R 对象,其中元素按二维矩形布局排列。它们包含相同原子类型的元素。虽然我们可以创建一个只包含字符或只包含逻辑值的矩阵,但它们并没有多大用处。我们使用包含数字元素的矩阵用于数学计算。

使用 matrix() 函数创建矩阵。

Syntax

在 R 中创建矩阵的基本语法为:

matrix(data, nrow, ncol, byrow, dimnames)

以下是所用参数的描述 -

  1. data 是成为矩阵数据元素的输入向量。

  2. nrow 是要创建的行数。

  3. ncol 是要创建的列数。

  4. byrow 是逻辑提示。如果为 TRUE,则按行排列输入向量元素。

  5. dimname 是分配给行和列的名称。

Example

创建一个以数字向量为输入的矩阵。

# Elements are arranged sequentially by row.
M <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(M)

# Elements are arranged sequentially by column.
N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)

# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")

P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
print(P)

当我们执行上述代码时,会产生以下结果 -

     [,1] [,2] [,3]
[1,]    3    4    5
[2,]    6    7    8
[3,]    9   10   11
[4,]   12   13   14
     [,1] [,2] [,3]
[1,]    3    7   11
[2,]    4    8   12
[3,]    5    9   13
[4,]    6   10   14
     col1 col2 col3
row1    3    4    5
row2    6    7    8
row3    9   10   11
row4   12   13   14

Accessing Elements of a Matrix

矩阵的元素可以通过使用该元素的列和行索引进行访问。我们考虑上面的矩阵 P 来找到下面的特定元素。

# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")

# Create the matrix.
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))

# Access the element at 3rd column and 1st row.
print(P[1,3])

# Access the element at 2nd column and 4th row.
print(P[4,2])

# Access only the  2nd row.
print(P[2,])

# Access only the 3rd column.
print(P[,3])

当我们执行上述代码时,会产生以下结果 -

[1] 5
[1] 13
col1 col2 col3
   6    7    8
row1 row2 row3 row4
   5    8   11   14

Matrix Computations

使用 R 运算符对矩阵执行各种数学运算。运算的结果也是一个矩阵。

参与运算的矩阵的维度(行数和列数)应相同。

Matrix Addition & Subtraction

# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)

# Add the matrices.
result <- matrix1 + matrix2
cat("Result of addition","\n")
print(result)

# Subtract the matrices
result <- matrix1 - matrix2
cat("Result of subtraction","\n")
print(result)

当我们执行上述代码时,会产生以下结果 -

     [,1] [,2] [,3]
[1,]    3   -1    2
[2,]    9    4    6
     [,1] [,2] [,3]
[1,]    5    0    3
[2,]    2    9    4
Result of addition
     [,1] [,2] [,3]
[1,]    8   -1    5
[2,]   11   13   10
Result of subtraction
     [,1] [,2] [,3]
[1,]   -2   -1   -1
[2,]    7   -5    2

Matrix Multiplication & Division

# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)

# Multiply the matrices.
result <- matrix1 * matrix2
cat("Result of multiplication","\n")
print(result)

# Divide the matrices
result <- matrix1 / matrix2
cat("Result of division","\n")
print(result)

当我们执行上述代码时,会产生以下结果 -

     [,1] [,2] [,3]
[1,]    3   -1    2
[2,]    9    4    6
     [,1] [,2] [,3]
[1,]    5    0    3
[2,]    2    9    4
Result of multiplication
     [,1] [,2] [,3]
[1,]   15    0    6
[2,]   18   36   24
Result of division
     [,1]      [,2]      [,3]
[1,]  0.6      -Inf 0.6666667
[2,]  4.5 0.4444444 1.5000000

R - Arrays

数组是 R 数据对象,它可以在两个以上维度中存储数据。例如,如果我们创建一个维度为 (2, 3, 4) 的数组,则会创建 4 个矩形矩阵,每个矩阵有 2 行和 3 列。数组只能存储数据类型。

使用 array() 函数创建数组。它将向量作为输入,并使用 dim 参数中的值来创建数组。

Example

以下示例创建了两个 3x3 矩阵的数组,每个矩阵有 3 行和 3 列。

# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.
result <- array(c(vector1,vector2),dim = c(3,3,2))
print(result)

当我们执行上述代码时,会产生以下结果 -

, , 1

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

, , 2

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

Naming Columns and Rows

我们可以使用 dimnames 参数为数组中的行、列和矩阵命名。

# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
column.names <- c("COL1","COL2","COL3")
row.names <- c("ROW1","ROW2","ROW3")
matrix.names <- c("Matrix1","Matrix2")

# Take these vectors as input to the array.
result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,column.names,
   matrix.names))
print(result)

当我们执行上述代码时,会产生以下结果 -

, , Matrix1

     COL1 COL2 COL3
ROW1    5   10   13
ROW2    9   11   14
ROW3    3   12   15

, , Matrix2

     COL1 COL2 COL3
ROW1    5   10   13
ROW2    9   11   14
ROW3    3   12   15

Accessing Array Elements

# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
column.names <- c("COL1","COL2","COL3")
row.names <- c("ROW1","ROW2","ROW3")
matrix.names <- c("Matrix1","Matrix2")

# Take these vectors as input to the array.
result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,
   column.names, matrix.names))

# Print the third row of the second matrix of the array.
print(result[3,,2])

# Print the element in the 1st row and 3rd column of the 1st matrix.
print(result[1,3,1])

# Print the 2nd Matrix.
print(result[,,2])

当我们执行上述代码时,会产生以下结果 -

COL1 COL2 COL3
   3   12   15
[1] 13
     COL1 COL2 COL3
ROW1    5   10   13
ROW2    9   11   14
ROW3    3   12   15

Manipulating Array Elements

由于数组是由多维矩阵组成的,因此对数组元素的操作是通过访问矩阵的元素来执行的。

# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.
array1 <- array(c(vector1,vector2),dim = c(3,3,2))

# Create two vectors of different lengths.
vector3 <- c(9,1,0)
vector4 <- c(6,0,11,3,14,1,2,6,9)
array2 <- array(c(vector1,vector2),dim = c(3,3,2))

# create matrices from these arrays.
matrix1 <- array1[,,2]
matrix2 <- array2[,,2]

# Add the matrices.
result <- matrix1+matrix2
print(result)

当我们执行上述代码时,会产生以下结果 -

     [,1] [,2] [,3]
[1,]   10   20   26
[2,]   18   22   28
[3,]    6   24   30

Calculations Across Array Elements

我们可以使用 apply() 函数对数组中的元素进行计算。

Syntax

apply(x, margin, fun)

以下是所用参数的描述 -

  1. x is an array.

  2. margin 是所用数据集的名称。

  3. fun 是要在数组元素上应用的函数。

Example

我们在下面使用 apply() 函数来计算跨所有矩阵的数组行中的元素的总和。

# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.
new.array <- array(c(vector1,vector2),dim = c(3,3,2))
print(new.array)

# Use apply to calculate the sum of the rows across all the matrices.
result <- apply(new.array, c(1), sum)
print(result)

当我们执行上述代码时,会产生以下结果 -

, , 1

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

, , 2

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

[1] 56 68 60

R - Factors

因子是用于对数据进行分类并将其存储为级别的 data 对象。它们可以存储字符串和整数。它们在具有有限数量唯一值(例如“男性”、“女性”和 True、False 等)的列中很有用。它们在用于统计建模的数据分析中很有用。

通过将向量作为输入,使用 factor () 函数创建因子。

Example

# Create a vector as input.
data <- c("East","West","East","North","North","East","West","West","West","East","North")

print(data)
print(is.factor(data))

# Apply the factor function.
factor_data <- factor(data)

print(factor_data)
print(is.factor(factor_data))

当我们执行上述代码时,会产生以下结果 -

[1] "East"  "West"  "East"  "North" "North" "East"  "West"  "West"  "West"  "East" "North"
[1] FALSE
[1] East  West  East  North North East  West  West  West  East  North
Levels: East North West
[1] TRUE

Factors in Data Frame

在创建任何带有文本数据列的数据框架时,R 将文本列视为分类数据,并在其上创建因子。

# Create the vectors for data frame.
height <- c(132,151,162,139,166,147,122)
weight <- c(48,49,66,53,67,52,40)
gender <- c("male","male","female","female","male","female","male")

# Create the data frame.
input_data <- data.frame(height,weight,gender)
print(input_data)

# Test if the gender column is a factor.
print(is.factor(input_data$gender))

# Print the gender column so see the levels.
print(input_data$gender)

当我们执行上述代码时,会产生以下结果 -

  height weight gender
1    132     48   male
2    151     49   male
3    162     66 female
4    139     53 female
5    166     67   male
6    147     52 female
7    122     40   male
[1] TRUE
[1] male   male   female female male   female male
Levels: female male

Changing the Order of Levels

可以通过再次应用 factor 函数并指定新级别顺序来更改因子中级别的顺序。

data <- c("East","West","East","North","North","East","West",
   "West","West","East","North")
# Create the factors
factor_data <- factor(data)
print(factor_data)

# Apply the factor function with required order of the level.
new_order_data <- factor(factor_data,levels = c("East","West","North"))
print(new_order_data)

当我们执行上述代码时,会产生以下结果 -

 [1] East  West  East  North North East  West  West  West  East  North
Levels: East North West
 [1] East  West  East  North North East  West  West  West  East  North
Levels: East West North

Generating Factor Levels

我们可以使用 gl() 函数生成因子级别。它将两个整数作为输入,以指示有多少个级别以及每个级别出现多少次。

Syntax

gl(n, k, labels)

以下是所用参数的描述 -

  1. n 是给出级别数的整数。

  2. k 是一个给出复制量的整数。

  3. labels 是对结果因子水平的标签的向量。

Example

v <- gl(3, 4, labels = c("Tampa", "Seattle","Boston"))
print(v)

当我们执行上述代码时,会产生以下结果 -

Tampa   Tampa   Tampa   Tampa   Seattle Seattle Seattle Seattle Boston
[10] Boston  Boston  Boston
Levels: Tampa Seattle Boston

R - Data Frames

数据框是表格或二维数组类似结构,其中每列含有一个变量的值,每行包含每列的一组值。

以下是数据框的特征。

  1. 列名不应为空。

  2. 行名应唯一。

  3. 存储在数据框中的数据可以是数字、因子或字符类型。

  4. 每列应包含相同数量的数据项。

Create Data Frame

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)
# Print the data frame.
print(emp.data)

当我们执行上述代码时,会产生以下结果 -

 emp_id    emp_name     salary     start_date
1     1     Rick        623.30     2012-01-01
2     2     Dan         515.20     2013-09-23
3     3     Michelle    611.00     2014-11-15
4     4     Ryan        729.00     2014-05-11
5     5     Gary        843.25     2015-03-27

Get the Structure of the Data Frame

可以使用 str() 函数查看数据框的结构。

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)
# Get the structure of the data frame.
str(emp.data)

当我们执行上述代码时,会产生以下结果 -

'data.frame':   5 obs. of  4 variables:
 $ emp_id    : int  1 2 3 4 5
 $ emp_name  : chr  "Rick" "Dan" "Michelle" "Ryan" ...
 $ salary    : num  623 515 611 729 843
 $ start_date: Date, format: "2012-01-01" "2013-09-23" "2014-11-15" "2014-05-11" ...

Summary of Data in Data Frame

可以通过应用 summary() 函数获取数据的统计摘要和性质。

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)
# Print the summary.
print(summary(emp.data))

当我们执行上述代码时,会产生以下结果 -

     emp_id    emp_name             salary        start_date
 Min.   :1   Length:5           Min.   :515.2   Min.   :2012-01-01
 1st Qu.:2   Class :character   1st Qu.:611.0   1st Qu.:2013-09-23
 Median :3   Mode  :character   Median :623.3   Median :2014-05-11
 Mean   :3                      Mean   :664.4   Mean   :2014-01-14
 3rd Qu.:4                      3rd Qu.:729.0   3rd Qu.:2014-11-15
 Max.   :5                      Max.   :843.2   Max.   :2015-03-27

Extract Data from Data Frame

使用列名从数据框提取特定列。

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01","2013-09-23","2014-11-15","2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)
# Extract Specific columns.
result <- data.frame(emp.data$emp_name,emp.data$salary)
print(result)

当我们执行上述代码时,会产生以下结果 -

  emp.data.emp_name emp.data.salary
1              Rick          623.30
2               Dan          515.20
3          Michelle          611.00
4              Ryan          729.00
5              Gary          843.25

提取前两行,然后提取所有列

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)
# Extract first two rows.
result <- emp.data[1:2,]
print(result)

当我们执行上述代码时,会产生以下结果 -

  emp_id    emp_name   salary    start_date
1      1     Rick      623.3     2012-01-01
2      2     Dan       515.2     2013-09-23

提取 3 和 5 行,以及 2 和 4 列

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

	start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)

# Extract 3rd and 5th row with 2nd and 4th column.
result <- emp.data[c(3,5),c(2,4)]
print(result)

当我们执行上述代码时,会产生以下结果 -

  emp_name start_date
3 Michelle 2014-11-15
5     Gary 2015-03-27

Expand Data Frame

可以通过添加列和行来扩展数据框。

Add Column

只需使用新列名添加列向量。

# Create the data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)

# Add the "dept" coulmn.
emp.data$dept <- c("IT","Operations","IT","HR","Finance")
v <- emp.data
print(v)

当我们执行上述代码时,会产生以下结果 -

  emp_id   emp_name    salary    start_date       dept
1     1    Rick        623.30    2012-01-01       IT
2     2    Dan         515.20    2013-09-23       Operations
3     3    Michelle    611.00    2014-11-15       IT
4     4    Ryan        729.00    2014-05-11       HR
5     5    Gary        843.25    2015-03-27       Finance

Add Row

若要向现有数据框永久添加更多行,我们需要以与现有数据框相同的结构引进新行,并使用 rbind() 函数。

在下面的示例中,我们创建一个包含新行的 data 框,并将其与现有 data 框合并以创建最终 data 框。

# Create the first data frame.
emp.data <- data.frame(
   emp_id = c (1:5),
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),

   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   dept = c("IT","Operations","IT","HR","Finance"),
   stringsAsFactors = FALSE
)

# Create the second data frame
emp.newdata <- 	data.frame(
   emp_id = c (6:8),
   emp_name = c("Rasmi","Pranab","Tusar"),
   salary = c(578.0,722.5,632.8),
   start_date = as.Date(c("2013-05-21","2013-07-30","2014-06-17")),
   dept = c("IT","Operations","Fianance"),
   stringsAsFactors = FALSE
)

# Bind the two data frames.
emp.finaldata <- rbind(emp.data,emp.newdata)
print(emp.finaldata)

当我们执行上述代码时,会产生以下结果 -

  emp_id     emp_name    salary     start_date       dept
1      1     Rick        623.30     2012-01-01       IT
2      2     Dan         515.20     2013-09-23       Operations
3      3     Michelle    611.00     2014-11-15       IT
4      4     Ryan        729.00     2014-05-11       HR
5      5     Gary        843.25     2015-03-27       Finance
6      6     Rasmi       578.00     2013-05-21       IT
7      7     Pranab      722.50     2013-07-30       Operations
8      8     Tusar       632.80     2014-06-17       Fianance

R - Packages

R 包是 R 函数、已编译代码和样本数据的集合。它们被存储在 R 环境中名为 "library" 的目录下。默认情况下,R 在安装过程中安装了一组包。当它们被用于某些特定目的时,后期还会添加更多的包。当我们启动 R 控制台时,默认情况下只有默认包可用。必须显式加载其他已安装的包,才能让将要使用它们的 R 程序访问它们。

R 语言中所有可用的包均在 R Packages. 列出。

下方是用于检查、验证和使用 R 包的命令列表。

Check Available R Packages

获取包含 R 包的库位置

.libPaths()

当我们执行以上代码时,它会生成以下结果。结果可能根据电脑的本地设置有所不同。

[2] "C:/Program Files/R/R-3.2.2/library"

Get the list of all the packages installed

library()

当我们执行以上代码时,它会生成以下结果。结果可能根据电脑的本地设置有所不同。

Packages in library ‘C:/Program Files/R/R-3.2.2/library’:

base                    The R Base Package
boot                    Bootstrap Functions (Originally by Angelo Canty
                        for S)
class                   Functions for Classification
cluster                 "Finding Groups in Data": Cluster Analysis
                        Extended Rousseeuw et al.
codetools               Code Analysis Tools for R
compiler                The R Compiler Package
datasets                The R Datasets Package
foreign                 Read Data Stored by 'Minitab', 'S', 'SAS',
                        'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ...
graphics                The R Graphics Package
grDevices               The R Graphics Devices and Support for Colours
                        and Fonts
grid                    The Grid Graphics Package
KernSmooth              Functions for Kernel Smoothing Supporting Wand
                        & Jones (1995)
lattice                 Trellis Graphics for R
MASS                    Support Functions and Datasets for Venables and
                        Ripley's MASS
Matrix                  Sparse and Dense Matrix Classes and Methods
methods                 Formal Methods and Classes
mgcv                    Mixed GAM Computation Vehicle with GCV/AIC/REML
                        Smoothness Estimation
nlme                    Linear and Nonlinear Mixed Effects Models
nnet                    Feed-Forward Neural Networks and Multinomial
                        Log-Linear Models
parallel                Support for Parallel computation in R
rpart                   Recursive Partitioning and Regression Trees
spatial                 Functions for Kriging and Point Pattern
                        Analysis
splines                 Regression Spline Functions and Classes
stats                   The R Stats Package
stats4                  Statistical Functions using S4 Classes
survival                Survival Analysis
tcltk                   Tcl/Tk Interface
tools                   Tools for Package Development
utils                   The R Utils Package

获取 R 环境中当前加载的所有包

search()

当我们执行以上代码时,它会生成以下结果。结果可能根据电脑的本地设置有所不同。

[1] ".GlobalEnv"        "package:stats"     "package:graphics"
[4] "package:grDevices" "package:utils"     "package:datasets"
[7] "package:methods"   "Autoloads"         "package:base"

Install a New Package

有两种添加新 R 包的方法。一种是直接从 CRAN 目录安装,另一种是将包下载至本地系统并手动安装。

Install directly from CRAN

以下命令直接从 CRAN 网页获取包,并将包安装至 R 环境。系统可能会提示你选择最近的镜像。选择一个适合你所在位置的镜像。

 install.packages("Package Name")

# Install the package named "XML".
 install.packages("XML")

Install package manually

前往链接 R Packages 下载所需的包。将包另存为 .zip 文件至本地系统中的适当位置。

现在,你可以运行以下命令以在 R 环境中安装此包。

install.packages(file_name_with_path, repos = NULL, type = "source")

# Install the package named "XML"
install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")

Load Package to Library

在代码中使用包之前,必须先将其加载至当前 R 环境。你还可以加载之前已安装但当前环境中不可用的包。

使用以下命令加载包 −

library("package Name", lib.loc = "path to library")

# Load the package named "XML"
install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")

R - Data Reshaping

R 中的数据重塑涉及更改按行和列组织数据的方式。在 R 中执行数据处理时,大多数情况下会将输入数据作为数据框架。从数据框架的行和列中提取数据非常容易,但在某些情况下,我们需要数据框架采用与接收到的格式不同的格式。R 有许多函数可以在数据框架中将行拆分为列并反之亦然。

Joining Columns and Rows in a Data Frame

我们可以使用 cbind()*function. Also we can merge two data frames using *rbind() 函数连接多个向量以创建数据框架。

# Create vector objects.
city <- c("Tampa","Seattle","Hartford","Denver")
state <- c("FL","WA","CT","CO")
zipcode <- c(33602,98104,06161,80294)

# Combine above three vectors into one data frame.
addresses <- cbind(city,state,zipcode)

# Print a header.
cat("# # # # The First data frame\n")

# Print the data frame.
print(addresses)

# Create another data frame with similar columns
new.address <- data.frame(
   city = c("Lowry","Charlotte"),
   state = c("CO","FL"),
   zipcode = c("80230","33949"),
   stringsAsFactors = FALSE
)

# Print a header.
cat("# # # The Second data frame\n")

# Print the data frame.
print(new.address)

# Combine rows form both the data frames.
all.addresses <- rbind(addresses,new.address)

# Print a header.
cat("# # # The combined data frame\n")

# Print the result.
print(all.addresses)

当我们执行上述代码时,会产生以下结果 -

# # # # The First data frame
     city       state zipcode
[1,] "Tampa"    "FL"  "33602"
[2,] "Seattle"  "WA"  "98104"
[3,] "Hartford" "CT"   "6161"
[4,] "Denver"   "CO"  "80294"

# # # The Second data frame
       city       state   zipcode
1      Lowry      CO      80230
2      Charlotte  FL      33949

# # # The combined data frame
       city      state zipcode
1      Tampa     FL    33602
2      Seattle   WA    98104
3      Hartford  CT     6161
4      Denver    CO    80294
5      Lowry     CO    80230
6     Charlotte  FL    33949

Merging Data Frames

我们可以使用 merge() 函数合并两个数据框架。数据框架在合并发生时必须具有相同列名。

在以下示例中,我们考虑库“MASS”中提供的皮马印第安女性糖尿病数据集。我们根据血压 (“bp”) 和体重指数 (“bmi”) 的值合并两个数据集。在选择这两列进行合并时,两个数据集中的这两个变量值匹配的记录将合并在一起,形成一个单独的数据框架。

library(MASS)
merged.Pima <- merge(x = Pima.te, y = Pima.tr,
   by.x = c("bp", "bmi"),
   by.y = c("bp", "bmi")
)
print(merged.Pima)
nrow(merged.Pima)

当我们执行上述代码时,会产生以下结果 -

   bp  bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y ped.y
1  60 33.8       1   117     23 0.466    27     No       2   125     20 0.088
2  64 29.7       2    75     24 0.370    33     No       2   100     23 0.368
3  64 31.2       5   189     33 0.583    29    Yes       3   158     13 0.295
4  64 33.2       4   117     27 0.230    24     No       1    96     27 0.289
5  66 38.1       3   115     39 0.150    28     No       1   114     36 0.289
6  68 38.5       2   100     25 0.324    26     No       7   129     49 0.439
7  70 27.4       1   116     28 0.204    21     No       0   124     20 0.254
8  70 33.1       4    91     32 0.446    22     No       9   123     44 0.374
9  70 35.4       9   124     33 0.282    34     No       6   134     23 0.542
10 72 25.6       1   157     21 0.123    24     No       4    99     17 0.294
11 72 37.7       5    95     33 0.370    27     No       6   103     32 0.324
12 74 25.9       9   134     33 0.460    81     No       8   126     38 0.162
13 74 25.9       1    95     21 0.673    36     No       8   126     38 0.162
14 78 27.6       5    88     30 0.258    37     No       6   125     31 0.565
15 78 27.6      10   122     31 0.512    45     No       6   125     31 0.565
16 78 39.4       2   112     50 0.175    24     No       4   112     40 0.236
17 88 34.5       1   117     24 0.403    40    Yes       4   127     11 0.598
   age.y type.y
1     31     No
2     21     No
3     24     No
4     21     No
5     21     No
6     43    Yes
7     36    Yes
8     40     No
9     29    Yes
10    28     No
11    55     No
12    39     No
13    39     No
14    49    Yes
15    49    Yes
16    38     No
17    28     No
[1] 17

Melting and Casting

R 编程最有趣的方面之一是分多个步骤更改数据形状以获得所需形状。用于执行此操作的函数称为 melt()cast()

我们考虑库“MASS”中存在的称为 ships 的数据集。

library(MASS)
print(ships)

当我们执行上述代码时,会产生以下结果 -

     type year   period   service   incidents
1     A   60     60        127         0
2     A   60     75         63         0
3     A   65     60       1095         3
4     A   65     75       1095         4
5     A   70     60       1512         6
.............
.............
8     A   75     75       2244         11
9     B   60     60      44882         39
10    B   60     75      17176         29
11    B   65     60      28609         58
............
............
17    C   60     60      1179          1
18    C   60     75       552          1
19    C   65     60       781          0
............
............

Melt the Data

现在,我们熔化数据对其进行组织,将除类型和年份以外的所有列转换为多行。

molten.ships <- melt(ships, id = c("type","year"))
print(molten.ships)

当我们执行上述代码时,会产生以下结果 -

      type year  variable  value
1      A   60    period      60
2      A   60    period      75
3      A   65    period      60
4      A   65    period      75
............
............
9      B   60    period      60
10     B   60    period      75
11     B   65    period      60
12     B   65    period      75
13     B   70    period      60
...........
...........
41     A   60    service    127
42     A   60    service     63
43     A   65    service   1095
...........
...........
70     D   70    service   1208
71     D   75    service      0
72     D   75    service   2051
73     E   60    service     45
74     E   60    service      0
75     E   65    service    789
...........
...........
101    C   70    incidents    6
102    C   70    incidents    2
103    C   75    incidents    0
104    C   75    incidents    1
105    D   60    incidents    0
106    D   60    incidents    0
...........
...........

Cast the Molten Data

我们可以将熔融数据转换为新形式,其中创建了每个年份中每种船舶类型的汇总。这是使用 cast() 函数完成的。

recasted.ship <- cast(molten.ships, type+year~variable,sum)
print(recasted.ship)

当我们执行上述代码时,会产生以下结果 -

     type year  period  service  incidents
1     A   60    135       190      0
2     A   65    135      2190      7
3     A   70    135      4865     24
4     A   75    135      2244     11
5     B   60    135     62058     68
6     B   65    135     48979    111
7     B   70    135     20163     56
8     B   75    135      7117     18
9     C   60    135      1731      2
10    C   65    135      1457      1
11    C   70    135      2731      8
12    C   75    135       274      1
13    D   60    135       356      0
14    D   65    135       480      0
15    D   70    135      1557     13
16    D   75    135      2051      4
17    E   60    135        45      0
18    E   65    135      1226     14
19    E   70    135      3318     17
20    E   75    135       542      1

R - CSV Files

在 R 中,我们可以阅读存储在 R 环境外部的文件中的数据。我们还可以将数据写入将被操作系统存储和访问的文件中。R 可以读写各种文件格式,如 csv、excel、xml 等。

在本章中,我们将学习如何从 csv 文件读取数据,然后将数据写入 csv 文件。该文件应位于当前工作目录中,以便 R 可以读取它。当然,我们也可以设置自己的目录并从中读取文件。

Getting and Setting the Working Directory

你可以使用 getwd() 函数查看 R 工作区指向哪个目录。你还可以使用 setwd() 函数设置新的工作目录。

# Get and print current working directory.
print(getwd())

# Set current working directory.
setwd("/web/com")

# Get and print current working directory.
print(getwd())

当我们执行上述代码时,会产生以下结果 -

[1] "/web/com/1441086124_2016"
[1] "/web/com"

此结果取决于你的操作系统和你在其上工作的当前目录。

Input as CSV File

csv 文件是一个文本文件,其中各列中的值由逗号分隔。让我们考虑名为 input.csv 的文件中存在的以下数据。

您可以通过复制并粘贴此数据来使用 Windows 记事本创建此文件。在记事本中使用另存为所有文件( . ) 选项将文件保存为 input.csv

id,name,salary,start_date,dept
1,Rick,623.3,2012-01-01,IT
2,Dan,515.2,2013-09-23,Operations
3,Michelle,611,2014-11-15,IT
4,Ryan,729,2014-05-11,HR
5,Gary,843.25,2015-03-27,Finance
6,Nina,578,2013-05-21,IT
7,Simon,632.8,2013-07-30,Operations
8,Guru,722.5,2014-06-17,Finance

Reading a CSV File

以下是 read.csv() 函数的一个简单示例,用于读取当前工作目录中可用的 CSV 文件 −

data <- read.csv("input.csv")
print(data)

当我们执行上述代码时,会产生以下结果 -

      id,   name,    salary,   start_date,     dept
1      1    Rick     623.30    2012-01-01      IT
2      2    Dan      515.20    2013-09-23      Operations
3      3    Michelle 611.00    2014-11-15      IT
4      4    Ryan     729.00    2014-05-11      HR
5     NA    Gary     843.25    2015-03-27      Finance
6      6    Nina     578.00    2013-05-21      IT
7      7    Simon    632.80    2013-07-30      Operations
8      8    Guru     722.50    2014-06-17      Finance

Analyzing the CSV File

默认情况下, read.csv() 函数将输出作为数据框。这可以很容易地检查如下所示。我们还可以检查列数和行数。

data <- read.csv("input.csv")

print(is.data.frame(data))
print(ncol(data))
print(nrow(data))

当我们执行上述代码时,会产生以下结果 -

[1] TRUE
[1] 5
[1] 8

一旦我们在数据框中读取数据,我们就可以应用以下部分中说明的适用于数据框的所有函数。

Get the maximum salary

# Create a data frame.
data <- read.csv("input.csv")

# Get the max salary from data frame.
sal <- max(data$salary)
print(sal)

当我们执行上述代码时,会产生以下结果 -

[1] 843.25

Get the details of the person with max salary

我们可以获取满足特定过滤条件的行,类似于 SQL 中的 where 子句。

# Create a data frame.
data <- read.csv("input.csv")

# Get the max salary from data frame.
sal <- max(data$salary)

# Get the person detail having max salary.
retval <- subset(data, salary == max(salary))
print(retval)

当我们执行上述代码时,会产生以下结果 -

      id    name  salary  start_date    dept
5     NA    Gary  843.25  2015-03-27    Finance

Get all the people working in IT department

# Create a data frame.
data <- read.csv("input.csv")

retval <- subset( data, dept == "IT")
print(retval)

当我们执行上述代码时,会产生以下结果 -

       id   name      salary   start_date   dept
1      1    Rick      623.3    2012-01-01   IT
3      3    Michelle  611.0    2014-11-15   IT
6      6    Nina      578.0    2013-05-21   IT

Get the persons in IT department whose salary is greater than 600

# Create a data frame.
data <- read.csv("input.csv")

info <- subset(data, salary > 600 & dept == "IT")
print(info)

当我们执行上述代码时,会产生以下结果 -

       id   name      salary   start_date   dept
1      1    Rick      623.3    2012-01-01   IT
3      3    Michelle  611.0    2014-11-15   IT

Get the people who joined on or after 2014

# Create a data frame.
data <- read.csv("input.csv")

retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01"))
print(retval)

当我们执行上述代码时,会产生以下结果 -

       id   name     salary   start_date    dept
3      3    Michelle 611.00   2014-11-15    IT
4      4    Ryan     729.00   2014-05-11    HR
5     NA    Gary     843.25   2015-03-27    Finance
8      8    Guru     722.50   2014-06-17    Finance

Writing into a CSV File

R 可以从现有数据框架创建 csv 文件。 write.csv() 函数用于创建 csv 文件。此文件会在工作目录中创建。

# Create a data frame.
data <- read.csv("input.csv")
retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01"))

# Write filtered data into a new file.
write.csv(retval,"output.csv")
newdata <- read.csv("output.csv")
print(newdata)

当我们执行上述代码时,会产生以下结果 -

  X      id   name      salary   start_date    dept
1 3      3    Michelle  611.00   2014-11-15    IT
2 4      4    Ryan      729.00   2014-05-11    HR
3 5     NA    Gary      843.25   2015-03-27    Finance
4 8      8    Guru      722.50   2014-06-17    Finance

此处 X 列来自数据集 newper。在写入文件时,可以使用附加参数将其删除。

# Create a data frame.
data <- read.csv("input.csv")
retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01"))

# Write filtered data into a new file.
write.csv(retval,"output.csv", row.names = FALSE)
newdata <- read.csv("output.csv")
print(newdata)

当我们执行上述代码时,会产生以下结果 -

      id    name      salary   start_date    dept
1      3    Michelle  611.00   2014-11-15    IT
2      4    Ryan      729.00   2014-05-11    HR
3     NA    Gary      843.25   2015-03-27    Finance
4      8    Guru      722.50   2014-06-17    Finance

R - Excel File

Microsoft Excel 是最广泛使用的电子表格程序,它以 .xls 或 .xlsx 格式存储数据。R 可以使用一些专门的 Excel 程序包直接读取这些文件。少数此类程序包有 - XLConnect、xlsx、gdata 等。我们将使用 xlsx 程序包。R 还可以利用此程序包写入 Excel 文件。

Install xlsx Package

您可以在 R 控制台使用以下命令安装“xlsx”程序包。它可能要求安装此程序包所依赖的一些其他程序包。使用要求的程序包名称按照相同的命令安装其他程序包。

install.packages("xlsx")

Verify and Load the "xlsx" Package

使用以下命令验证并加载“xlsx”程序包。

# Verify the package is installed.
any(grepl("xlsx",installed.packages()))

# Load the library into R workspace.
library("xlsx")

当运行脚本时,我们得到以下输出。

[1] TRUE
Loading required package: rJava
Loading required package: methods
Loading required package: xlsxjars

Input as xlsx File

打开 Microsoft Excel。复制并粘贴以下数据到名为 sheet1 的工作表中。

id	name      salary    start_date	dept
1	Rick	    623.3	  1/1/2012	   IT
2	Dan       515.2     9/23/2013    Operations
3	Michelle  611	     11/15/2014	IT
4	Ryan	    729	     5/11/2014	   HR
5	Gary	    43.25     3/27/2015  	Finance
6	Nina	    578       5/21/2013	   IT
7	Simon	    632.8	  7/30/2013	   Operations
8	Guru	    722.5	  6/17/2014	   Finance

此外,复制并粘贴以下数据到另一个工作表并将此工作表重命名为“city”。

name	    city
Rick	    Seattle
Dan       Tampa
Michelle  Chicago
Ryan	    Seattle
Gary	    Houston
Nina	    Boston
Simon	    Mumbai
Guru	    Dallas

将 Excel 文件保存为“input.xlsx”。您应该将其保存在 R 工作区的当前工作目录中。

Reading the Excel File

input.xlsx 通过使用 read.xlsx() 函数读取,如下所示。结果存储为 R 环境中的一个数据框。

# Read the first worksheet in the file input.xlsx.
data <- read.xlsx("input.xlsx", sheetIndex = 1)
print(data)

当我们执行上述代码时,会产生以下结果 -

      id,   name,     salary,   start_date,   dept
1      1    Rick      623.30    2012-01-01    IT
2      2    Dan       515.20    2013-09-23    Operations
3      3    Michelle  611.00    2014-11-15    IT
4      4    Ryan      729.00    2014-05-11    HR
5     NA    Gary      843.25    2015-03-27    Finance
6      6    Nina      578.00    2013-05-21    IT
7      7    Simon     632.80    2013-07-30    Operations
8      8    Guru      722.50    2014-06-17    Finance

R - Binary Files

二进制文件是一个仅以位和字节(0 和 1)形式存储信息的 file。它们不可读,因为其中的字节转换为包含许多其他不可打印字符的字符和符号。尝试使用任何文本编辑器读取二进制文件将显示类似于 Ø 和 ð 的字符。

二进制文件必须由特定程序读取才能使用。例如,Microsoft Word 程序的二进制文件只能由 Word 程序读取为人类可读的形式。这表明,除了人类可读文本之外,还有更多信息,例如字符格式和页码等,这些信息也与字母数字字符一起存储。最后,二进制文件是连续的字节序列。我们在文本文件中看到的换行符是连接第一行和下一行的字符。

有时,需要由 R 将其他程序生成的数据作为二进制文件处理。还需要 R 创建可以与其他程序共享的二进制文件。

R 有两个函数 WriteBin()readBin() 来创建和读取二进制文件。

Syntax

writeBin(object, con)
readBin(con, what, n )

以下是所用参数的描述 -

  1. con 是读取或写入二进制文件的连接对象。

  2. object 是要写入的二进制文件。

  3. what 是表示要读取的字节的模式,例如字符、整数等。

  4. n 是要从二进制文件读取的字节数。

Example

我们考虑 R 内置数据“mtcars”。首先,我们从中创建一个 csv 文件,并将其转换为二进制文件并将其存储为 OS 文件。接下来,我们将创建的此二进制文件读入 R。

Writing the Binary File

我们将数据框“mtcars”读作 csv 文件,然后作为二进制文件写入操作系统。

# Read the "mtcars" data frame as a csv file and store only the columns
   "cyl", "am" and "gear".
write.table(mtcars, file = "mtcars.csv",row.names = FALSE, na = "",
   col.names = TRUE, sep = ",")

# Store 5 records from the csv file as a new data frame.
new.mtcars <- read.table("mtcars.csv",sep = ",",header = TRUE,nrows = 5)

# Create a connection object to write the binary file using mode "wb".
write.filename = file("/web/com/binmtcars.dat", "wb")

# Write the column names of the data frame to the connection object.
writeBin(colnames(new.mtcars), write.filename)

# Write the records in each of the column to the file.
writeBin(c(new.mtcars$cyl,new.mtcars$am,new.mtcars$gear), write.filename)

# Close the file for writing so that it can be read by other program.
close(write.filename)

Reading the Binary File

上面创建的二进制文件将所有数据存储为连续字节。因此,我们将通过选择列名以及列值来读取它。

# Create a connection object to read the file in binary mode using "rb".
read.filename <- file("/web/com/binmtcars.dat", "rb")

# First read the column names. n = 3 as we have 3 columns.
column.names <- readBin(read.filename, character(),  n = 3)

# Next read the column values. n = 18 as we have 3 column names and 15 values.
read.filename <- file("/web/com/binmtcars.dat", "rb")
bindata <- readBin(read.filename, integer(),  n = 18)

# Print the data.
print(bindata)

# Read the values from 4th byte to 8th byte which represents "cyl".
cyldata = bindata[4:8]
print(cyldata)

# Read the values form 9th byte to 13th byte which represents "am".
amdata = bindata[9:13]
print(amdata)

# Read the values form 9th byte to 13th byte which represents "gear".
geardata = bindata[14:18]
print(geardata)

# Combine all the read values to a dat frame.
finaldata = cbind(cyldata, amdata, geardata)
colnames(finaldata) = column.names
print(finaldata)

当我们执行上述代码时,它会产生以下结果和图表:

 [1]    7108963 1728081249    7496037          6          6          4
 [7]          6          8          1          1          1          0
[13]          0          4          4          4          3          3

[1] 6 6 4 6 8

[1] 1 1 1 0 0

[1] 4 4 4 3 3

     cyl am gear
[1,]   6  1    4
[2,]   6  1    4
[3,]   4  1    4
[4,]   6  0    3
[5,]   8  0    3

正如我们所看到的,我们通过在 R 中读取二进制文件获取了原始数据。

R - XML Files

XML 是一种共享文件格式和数据于万维网、内部网和其他地方(使用标准 ASCII 文本)的文件格式。它代表可扩展标记语言 (XML)。类似于 HTML,它包含标记标签。但与 HTML(其中标记标签描述页面的结构)不同,在 XML 中标记标签描述包含在文件中数据的含义。

你可以使用 “XML” 包在 R 中读取 XML 文件。可以使用以下命令安装此包。

install.packages("XML")

Input Data

通过将以下数据复制到记事本之类的文本编辑器中创建 XML 文件。保存文件并使用 .xml 扩展名,然后选择 all files( . ) 作为文件类型。

<RECORDS>
   <EMPLOYEE>
      <ID>1</ID>
      <NAME>Rick</NAME>
      <SALARY>623.3</SALARY>
      <STARTDATE>1/1/2012</STARTDATE>
      <DEPT>IT</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>2</ID>
      <NAME>Dan</NAME>
      <SALARY>515.2</SALARY>
      <STARTDATE>9/23/2013</STARTDATE>
      <DEPT>Operations</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>3</ID>
      <NAME>Michelle</NAME>
      <SALARY>611</SALARY>
      <STARTDATE>11/15/2014</STARTDATE>
      <DEPT>IT</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>4</ID>
      <NAME>Ryan</NAME>
      <SALARY>729</SALARY>
      <STARTDATE>5/11/2014</STARTDATE>
      <DEPT>HR</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>5</ID>
      <NAME>Gary</NAME>
      <SALARY>843.25</SALARY>
      <STARTDATE>3/27/2015</STARTDATE>
      <DEPT>Finance</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>6</ID>
      <NAME>Nina</NAME>
      <SALARY>578</SALARY>
      <STARTDATE>5/21/2013</STARTDATE>
      <DEPT>IT</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>7</ID>
      <NAME>Simon</NAME>
      <SALARY>632.8</SALARY>
      <STARTDATE>7/30/2013</STARTDATE>
      <DEPT>Operations</DEPT>
   </EMPLOYEE>

   <EMPLOYEE>
      <ID>8</ID>
      <NAME>Guru</NAME>
      <SALARY>722.5</SALARY>
      <STARTDATE>6/17/2014</STARTDATE>
      <DEPT>Finance</DEPT>
   </EMPLOYEE>

</RECORDS>

Reading XML File

使用 xmlParse() 函数通过 R 读取 XML 文件。它作为列表存储在 R 中。

# Load the package required to read XML files.
library("XML")

# Also load the other required package.
library("methods")

# Give the input file name to the function.
result <- xmlParse(file = "input.xml")

# Print the result.
print(result)

当我们执行上述代码时,会产生以下结果 -

1
Rick
623.3
1/1/2012
IT

2
Dan
515.2
9/23/2013
Operations

3
Michelle
611
11/15/2014
IT

4
Ryan
729
5/11/2014
HR

5
Gary
843.25
3/27/2015
Finance

6
Nina
578
5/21/2013
IT

7
Simon
632.8
7/30/2013
Operations

8
Guru
722.5
6/17/2014
Finance

Get Number of Nodes Present in XML File

# Load the packages required to read XML files.
library("XML")
library("methods")

# Give the input file name to the function.
result <- xmlParse(file = "input.xml")

# Exract the root node form the xml file.
rootnode <- xmlRoot(result)

# Find number of nodes in the root.
rootsize <- xmlSize(rootnode)

# Print the result.
print(rootsize)

当我们执行上述代码时,会产生以下结果 -

output
[1] 8

Details of the First Node

让我们查看已解析文件的第一个记录。它将向我们提供顶级节点中存在的各种元素的思路。

# Load the packages required to read XML files.
library("XML")
library("methods")

# Give the input file name to the function.
result <- xmlParse(file = "input.xml")

# Exract the root node form the xml file.
rootnode <- xmlRoot(result)

# Print the result.
print(rootnode[1])

当我们执行上述代码时,会产生以下结果 -

$EMPLOYEE
   1
   Rick
   623.3
   1/1/2012
   IT


attr(,"class")
[1] "XMLInternalNodeList" "XMLNodeList"

Get Different Elements of a Node

# Load the packages required to read XML files.
library("XML")
library("methods")

# Give the input file name to the function.
result <- xmlParse(file = "input.xml")

# Exract the root node form the xml file.
rootnode <- xmlRoot(result)

# Get the first element of the first node.
print(rootnode[[1]][[1]])

# Get the fifth element of the first node.
print(rootnode[[1]][[5]])

# Get the second element of the third node.
print(rootnode[[3]][[2]])

当我们执行上述代码时,会产生以下结果 -

1
IT
Michelle

XML to Data Frame

若要有效地处理大型文件中的数据,我们会将 XML 文件中的数据作为数据框读取。然后处理数据框用于进行数据分析。

# Load the packages required to read XML files.
library("XML")
library("methods")

# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)

当我们执行上述代码时,会产生以下结果 -

      ID    NAME     SALARY    STARTDATE       DEPT
1      1    Rick     623.30    2012-01-01      IT
2      2    Dan      515.20    2013-09-23      Operations
3      3    Michelle 611.00    2014-11-15      IT
4      4    Ryan     729.00    2014-05-11      HR
5     NA    Gary     843.25    2015-03-27      Finance
6      6    Nina     578.00    2013-05-21      IT
7      7    Simon    632.80    2013-07-30      Operations
8      8    Guru     722.50    2014-06-17      Finance

由于数据现在可用作数据框,我们可以使用与数据框有关的函数来读取和操作文件。

R - JSON Files

JSON 文件以人类可读的格式将数据存储为文本。Json 代表 JavaScript 对象表示法。R 可以使用 rjson 包来读取 JSON 文件。

Install rjson Package

在 R 控制台中,你可以发出以下命令来安装 rjson 包。

install.packages("rjson")

Input Data

通过将以下数据复制到记事本等文本编辑器中创建 JSON 文件。使用 .json 扩展名和文件类型 all files( . ) 保存文件。

{
   "ID":["1","2","3","4","5","6","7","8" ],
   "Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
   "Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],

   "StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
      "7/30/2013","6/17/2014"],
   "Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}

Read the JSON File

JSON 文件由 R 使用 JSON() 中的功能读取。它存储为 R 中的列表。

# Load the package required to read JSON files.
library("rjson")

# Give the input file name to the function.
result <- fromJSON(file = "input.json")

# Print the result.
print(result)

当我们执行上述代码时,会产生以下结果 -

$ID
[1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"

$Name
[1] "Rick"     "Dan"      "Michelle" "Ryan"     "Gary"     "Nina"     "Simon"    "Guru"

$Salary
[1] "623.3"  "515.2"  "611"    "729"    "843.25" "578"    "632.8"  "722.5"

$StartDate
[1] "1/1/2012"   "9/23/2013"  "11/15/2014" "5/11/2014"  "3/27/2015"  "5/21/2013"
   "7/30/2013"  "6/17/2014"

$Dept
[1] "IT"         "Operations" "IT"         "HR"         "Finance"    "IT"
   "Operations" "Finance"

Convert JSON to a Data Frame

我们可以使用 as.data.frame() 函数将上面提取的数据转换为 R 数据框以进行进一步分析。

# Load the package required to read JSON files.
library("rjson")

# Give the input file name to the function.
result <- fromJSON(file = "input.json")

# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)

print(json_data_frame)

当我们执行上述代码时,会产生以下结果 -

      id,   name,    salary,   start_date,     dept
1      1    Rick     623.30    2012-01-01      IT
2      2    Dan      515.20    2013-09-23      Operations
3      3    Michelle 611.00    2014-11-15      IT
4      4    Ryan     729.00    2014-05-11      HR
5     NA    Gary     843.25    2015-03-27      Finance
6      6    Nina     578.00    2013-05-21      IT
7      7    Simon    632.80    2013-07-30      Operations
8      8    Guru     722.50    2014-06-17      Finance

R - Web Data

许多网站提供数据供其用户使用。例如,世界卫生组织 (WHO) 以 CSV、txt 和 XML 文件的形式提供有关健康和医疗信息。使用 R 程序,我们可以以编程方式从这些网站中提取特定数据。在 R 中用于抓取网络数据的某些包为:“RCurl”、“XML”和“stringr”。它们用于连接 URL,识别文件所需的链接,并将它们下载到本地环境。

Install R Packages

以下包对于处理 URL 和文件链接是必需的。如果这些包在 R 环境中不可用,可以使用以下命令进行安装。

install.packages("RCurl")
install.packages("XML")
install.packages("stringr")
install.packages("plyr")

Input Data

我们将访问 URL weather data 并使用 R 下载 2015 年的 CSV 文件。

Example

我们将使用函数 getHTMLLinks() 收集文件的 URL。然后,我们将使用函数 download.file() 将文件保存到本地系统。由于我们将对多个文件重复应用相同的代码,因此我们将创建一个多次调用的函数。文件名以 R 列表对象的形式作为参数传递给此函数。

# Read the URL.
url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/"

# Gather the html links present in the webpage.
links <- getHTMLLinks(url)

# Identify only the links which point to the JCMB 2015 files.
filenames <- links[str_detect(links, "JCMB_2015")]

# Store the file names as a list.
filenames_list <- as.list(filenames)

# Create a function to download the files by passing the URL and filename list.
downloadcsv <- function (mainurl,filename) {
   filedetails <- str_c(mainurl,filename)
   download.file(filedetails,filename)
}

# Now apply the l_ply function and save the files into the current R working directory.
l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/")

Verify the File Download

运行以上代码后,您可以在当前 R 工作目录中找到以下文件。

"JCMB_2015.csv" "JCMB_2015_Apr.csv" "JCMB_2015_Feb.csv" "JCMB_2015_Jan.csv"
   "JCMB_2015_Mar.csv"

R - Databases

数据关系数据库系统以规范化格式存储。因此,要执行统计计算,我们需要非常高级和复杂的 SQL 查询。但 R 能轻松连接到许多关系数据库,如 MySQL、Oracle、SQL Server 等,并从这些数据库中获取记录,作为数据框。一旦数据可用于 R 环境,它就成为正常的 R 数据集,可以利用所有强大的程序包和函数来对其进行处理或分析。

在本教程中,我们将使用 MySQL 作为连接到 R 的参考数据库。

RMySQL Package

R 有一个名为“RMySQL”的内置程序包,该程序包提供与 MySQL 数据库之间的原生连接。您可以在 R 环境中使用以下命令安装此程序包。

install.packages("RMySQL")

Connecting R to MySql

安装完程序包后,我们在 R 中创建一个连接对象,以连接到数据库。它将用户名、密码、数据库名和主机名作为输入。

# Create a connection Object to MySQL database.
# We will connect to the sampel database named "sakila" that comes with MySql installation.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila',
   host = 'localhost')

# List the tables available in this database.
 dbListTables(mysqlconnection)

当我们执行上述代码时,会产生以下结果 -

 [1] "actor"                      "actor_info"
 [3] "address"                    "category"
 [5] "city"                       "country"
 [7] "customer"                   "customer_list"
 [9] "film"                       "film_actor"
[11] "film_category"              "film_list"
[13] "film_text"                  "inventory"
[15] "language"                   "nicer_but_slower_film_list"
[17] "payment"                    "rental"
[19] "sales_by_film_category"     "sales_by_store"
[21] "staff"                      "staff_list"
[23] "store"

Querying the Tables

我们可以使用函数 dbSendQuery() 查询 MySQL 中的数据库表。查询在 MySQL 中执行,并使用 R fetch() 函数返回结果集。最后,它作为数据框存储在 R 中。

# Query the "actor" tables to get all the rows.
result = dbSendQuery(mysqlconnection, "select * from actor")

# Store the result in a R data frame object. n = 5 is used to fetch first 5 rows.
data.frame = fetch(result, n = 5)
print(data.fame)

当我们执行上述代码时,会产生以下结果 -

        actor_id   first_name    last_name         last_update
1        1         PENELOPE      GUINESS           2006-02-15 04:34:33
2        2         NICK          WAHLBERG          2006-02-15 04:34:33
3        3         ED            CHASE             2006-02-15 04:34:33
4        4         JENNIFER      DAVIS             2006-02-15 04:34:33
5        5         JOHNNY        LOLLOBRIGIDA      2006-02-15 04:34:33

Query with Filter Clause

我们可以传递任何有效的 select 查询来获取结果。

result = dbSendQuery(mysqlconnection, "select * from actor where last_name = 'TORN'")

# Fetch all the records(with n = -1) and store it as a data frame.
data.frame = fetch(result, n = -1)
print(data)

当我们执行上述代码时,会产生以下结果 -

        actor_id    first_name     last_name         last_update
1        18         DAN            TORN              2006-02-15 04:34:33
2        94         KENNETH        TORN              2006-02-15 04:34:33
3       102         WALTER         TORN              2006-02-15 04:34:33

Updating Rows in the Tables

我们可以通过将 update 查询传递到 dbSendQuery() 函数中来更新 Mysql 表中的行。

dbSendQuery(mysqlconnection, "update mtcars set disp = 168.5 where hp = 110")

在执行上述代码后,我们可以看到在 MySql 环境中更新的表。

Inserting Data into the Tables

dbSendQuery(mysqlconnection,
   "insert into mtcars(row_names, mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb)
   values('New Mazda RX4 Wag', 21, 6, 168.5, 110, 3.9, 2.875, 17.02, 0, 1, 4, 4)"
)

在执行上述代码后,我们可以看到插入到 MySql 环境中的表的行。

Creating Tables in MySql

我们可以使用函数 dbWriteTable() 在 MySql 中创建表。如果表已经存在,它将覆盖该表,并采用数据框作为输入。

# Create the connection object to the database where we want to create the table.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila',
   host = 'localhost')

# Use the R data frame "mtcars" to create the table in MySql.
# All the rows of mtcars are taken inot MySql.
dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE)

在执行上述代码后,我们可以看到在 MySql 环境中创建的表。

Dropping Tables in MySql

我们可以通过将 drop table 语句传递到 dbSendQuery() 中来删除 MySql 数据库中的表,就像我们用于从表中查询数据一样。

dbSendQuery(mysqlconnection, 'drop table if exists mtcars')

在执行上述代码后,我们可以看到在 MySql 环境中删除了该表。

R - Pie Charts

R 编程语言有许多用于创建图表和图形的库。饼图是将值表示为带有不同颜色的圆形的切片的表示形式。这些切片带标签,并且每个切片对应的数字也显示在图表中。

在 R 中,使用 pie() 函数创建饼图,该函数接受正数作为向量输入。其他参数用于控制标签、颜色、标题等。

Syntax

使用 R 创建饼图的基本语法为:

pie(x, labels, radius, main, col, clockwise)

以下是所用参数的描述 -

  1. x 是饼图中使用的包含数值的向量。

  2. labels 用于对切片进行描述。

  3. radius 表示饼图圆的半径(−1 到 +1 之间的数值)。

  4. main 表示图表标题。

  5. col 表示色板。

  6. clockwise 是一个逻辑值,用于指出饼图是顺时针绘制还是逆时针绘制。

Example

仅使用输入矢量和标签就可以创建一个非常简单的饼状图。以下脚本将在当前 R 工作目录中创建和保存饼状图。

# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")

# Give the chart file a name.
png(file = "city.png")

# Plot the chart.
pie(x,labels)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

city

Pie Chart Title and Colors

我们可以通过向函数添加更多参数来扩展图表的功能。我们将使用参数 main 为图表添加标题,另一个参数是 col ,它将在绘制图表时使用彩虹色板。色板的长度应与图表的值的数量相同。因此,我们使用 length(x)。

Example

以下脚本将在当前 R 工作目录中创建和保存饼状图。

# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")

# Give the chart file a name.
png(file = "city_title_colours.jpg")

# Plot the chart with title and rainbow color pallet.
pie(x, labels, main = "City pie chart", col = rainbow(length(x)))

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

city title colours

Slice Percentages and Chart Legend

我们可以通过创建其他图表变量来添加切片百分比和图表图例。

# Create data for the graph.
x <-  c(21, 62, 10,53)
labels <-  c("London","New York","Singapore","Mumbai")

piepercent<- round(100*x/sum(x), 1)

# Give the chart file a name.
png(file = "city_percentage_legends.jpg")

# Plot the chart.
pie(x, labels = piepercent, main = "City pie chart",col = rainbow(length(x)))
legend("topright", c("London","New York","Singapore","Mumbai"), cex = 0.8,
   fill = rainbow(length(x)))

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

city percentage legends

3D Pie Chart

可以使用其他包来绘制三维饼状图。包 plotrix 有一个函数 pie3D() ,用于此目的。

# Get the library.
library(plotrix)

# Create data for the graph.
x <-  c(21, 62, 10,53)
lbl <-  c("London","New York","Singapore","Mumbai")

# Give the chart file a name.
png(file = "3d_pie_chart.jpg")

# Plot the chart.
pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

3d pie chart

R - Bar Charts

条形图以矩形条形表示数据,条形的长度与变量的值成正比。R 使用 barplot() 函数创建条形图。R 可以在条形图中绘制垂直条形和水平条形。在条形图中,每个条形都可以赋予不同的颜色。

Syntax

在 R 中创建条形图的基本语法为:

barplot(H,xlab,ylab,main, names.arg,col)

以下是所用参数的描述 -

  1. H 是条形图中使用的包含数字值的一个向量或矩阵。

  2. xlab 是 x 轴的标签。

  3. ylab 是 y 轴的标签。

  4. main 是条形图的标题。

  5. names.arg 是出现在每个条形下方名称的向量。

  6. col 用于给图表中的条形着色。

Example

仅使用输入向量和每个条形的名称创建简单的条形图。

如下脚本将在当前 R 工作目录中创建并保存条形图。

# Create the data for the chart
H <- c(7,12,28,3,41)

# Give the chart file a name
png(file = "barchart.png")

# Plot the bar chart
barplot(H)

# Save the file
dev.off()

当我们执行以上代码时,会产生以下结果 -

barchart

Bar Chart Labels, Title and Colors

可以通过添加更多参数来扩展条形图的功能。 main 参数用于添加 titlecol 参数用于给条形着色。 args.name 是一个向量,其值数与输入向量相同,用于描述每个条形的含义。

Example

如下脚本将在当前 R 工作目录中创建并保存条形图。

# Create the data for the chart
H <- c(7,12,28,3,41)
M <- c("Mar","Apr","May","Jun","Jul")

# Give the chart file a name
png(file = "barchart_months_revenue.png")

# Plot the bar chart
barplot(H,names.arg=M,xlab="Month",ylab="Revenue",col="blue",
main="Revenue chart",border="red")

# Save the file
dev.off()

当我们执行以上代码时,会产生以下结果 -

barchart months revenue

Group Bar Chart and Stacked Bar Chart

我们可以通过使用矩阵作为输入值,创建带有条形组和每个条形堆栈的条形图。

超过两个变量将表示为一个矩阵,用于创建组条形图和堆叠条形图。

# Create the input vectors.
colors = c("green","orange","brown")
months <- c("Mar","Apr","May","Jun","Jul")
regions <- c("East","West","North")

# Create the matrix of the values.
Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11), nrow = 3, ncol = 5, byrow = TRUE)

# Give the chart file a name
png(file = "barchart_stacked.png")

# Create the bar chart
barplot(Values, main = "total revenue", names.arg = months, xlab = "month", ylab = "revenue", col = colors)

# Add the legend to the chart
legend("topleft", regions, cex = 1.3, fill = colors)

# Save the file
dev.off()
barchart stacked

R - Boxplots

箱形图是衡量数据集中的数据分布状况的指标。它将数据集分成三个四分位数。此图表代表了数据集中最小值、最大值、中位数、第一四分位数和第三四分位数。它还可以通过绘制每个数据集的箱形图来比较不同数据集中的数据分布。

在 R 中使用 boxplot() 函数创建箱形图。

Syntax

在 R 中创建箱形图的基本语法为 -

boxplot(x, data, notch, varwidth, names, main)

以下是所用参数的描述 -

  1. x 是一个向量或一个公式。

  2. data 是数据框。

  3. notch 是一个逻辑值。设置为 TRUE 将绘制一个缺口。

  4. varwidth 是一个逻辑值。设置为 true 将绘制与样本大小成比例的箱宽度。

  5. names 是将打印在每个箱形图下的组标签。

  6. main 用于为图形命名。

Example

我们使用 R 环境中可用的数据集“mtcars”来创建一个基本的箱形图。我们来看看 mtcars 中的“mpg”和“cyl”列。

input <- mtcars[,c('mpg','cyl')]
print(head(input))

当我们执行以上代码时,会产生以下结果 -

                   mpg  cyl
Mazda RX4         21.0   6
Mazda RX4 Wag     21.0   6
Datsun 710        22.8   4
Hornet 4 Drive    21.4   6
Hornet Sportabout 18.7   8
Valiant           18.1   6

Creating the Boxplot

下面的脚本将创建一个反映 mpg(每加仑英里)和 cyl(气缸数)之间的关系的箱形图。

# Give the chart file a name.
png(file = "boxplot.png")

# Plot the chart.
boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders",
   ylab = "Miles Per Gallon", main = "Mileage Data")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

boxplot

Boxplot with Notch

我们可以绘制带缺口的箱形图,以找出不同数据组的中位数如何彼此匹配。

下面的脚本将为每个数据组创建一个带有缺口的箱形图。

# Give the chart file a name.
png(file = "boxplot_with_notch.png")

# Plot the chart.
boxplot(mpg ~ cyl, data = mtcars,
   xlab = "Number of Cylinders",
   ylab = "Miles Per Gallon",
   main = "Mileage Data",
   notch = TRUE,
   varwidth = TRUE,
   col = c("green","yellow","purple"),
   names = c("High","Medium","Low")
)
# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

boxplot with notch

R - Histograms

直方图表示按范围分段的变量值的频率。直方图类似于条形图,但区别在于它将值分组为连续范围。直方图中的每个条形表示该范围内存在的值的数量的高度。

R 使用 hist() 函数创建直方图。该函数以向量作为输入,并使用更多参数绘制直方图。

Syntax

使用 R 创建直方图的基本语法为:

hist(v,main,xlab,xlim,ylim,breaks,col,border)

以下是所用参数的描述 -

  1. v 是一个包含直方图中使用的数值的向量。

  2. main 表示图表标题。

  3. col 用于设置条形颜色。

  4. border 用于设置各个条形的边框颜色。

  5. xlab 用于给出 x 轴的描述。

  6. xlim 用于指定 x 轴上的值范围。

  7. ylim 用于指定 y 轴上的值范围。

  8. breaks 用于指定每个条形的宽度。

Example

使用 input 向量、标签、col 和边框参数创建简单的直方图。

下方给出的脚本将在当前 R 工作目录中创建并保存直方图。

# Create data for the graph.
v <-  c(9,13,21,8,36,22,12,41,31,33,19)

# Give the chart file a name.
png(file = "histogram.png")

# Create the histogram.
hist(v,xlab = "Weight",col = "yellow",border = "blue")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

histogram

Range of X and Y values

若要指定 X 轴和 Y 轴允许的值范围,我们可以使用 xlim 和 ylim 参数。

每个条形的宽度可以通过 breaks 决定。

# Create data for the graph.
v <- c(9,13,21,8,36,22,12,41,31,33,19)

# Give the chart file a name.
png(file = "histogram_lim_breaks.png")

# Create the histogram.
hist(v,xlab = "Weight",col = "green",border = "red", xlim = c(0,40), ylim = c(0,5),
   breaks = 5)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

histogram lim breaks

R - Line Graphs

折线图是一种通过在点之间绘制线段来连接一系列点的图形。这些点按其一个坐标值(通常是 x 坐标)排序。折线图通常用于识别数据中的趋势。

R 中的 plot() 函数用于创建折线图。

Syntax

在 R 中创建折线图的基本语法为:

plot(v,type,col,xlab,ylab)

以下是所用参数的描述 -

  1. v 是包含数值的向量。

  2. type 取值“p”表示仅绘制点,“l”表示仅绘制线,“o”表示同时绘制点和线。

  3. xlab 是 x 轴的标签。

  4. ylab 是 y 轴的标签。

  5. main 是图表标题。

  6. col 用于给点和线赋予颜色。

Example

使用输入向量和类型参数“O”创建简单的折线图。以下脚本将在当前 R 工作目录中创建和保存折线图。

# Create the data for the chart.
v <- c(7,12,28,3,41)

# Give the chart file a name.
png(file = "line_chart.jpg")

# Plot the bar chart.
plot(v,type = "o")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

line chart

Line Chart Title, Color and Labels

可以通过使用其他参数来扩展折线图的功能。我们给点和线添加颜色,给图表添加标题并给轴添加标签。

Example

# Create the data for the chart.
v <- c(7,12,28,3,41)

# Give the chart file a name.
png(file = "line_chart_label_colored.jpg")

# Plot the bar chart.
plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall",
   main = "Rain fall chart")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

line chart label colored

Multiple Lines in a Line Chart

可以在同一张图表上绘制多条线,方法是使用 lines() 函数。

在绘制完第一条线后,lines() 函数可以使用一个额外的向量作为输入,在图表中绘制第二条线。

# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)

# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")

# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall",
   main = "Rain fall chart")

lines(t, type = "o", col = "blue")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

line chart 2 lines

R - Scatterplots

散点图显示在笛卡尔平面上绘制的许多点。每个点代表两个变量的值。一个变量选择在水平轴中,另一个选择在垂直轴中。

利用 plot() 函数创建简单的散点图。

Syntax

在 R 中创建散点图的基本语法为 -

plot(x, y, main, xlab, ylab, xlim, ylim, axes)

以下是所用参数的描述 -

  1. x 是值的水平坐标的数据集。

  2. y 是值的垂直坐标的数据集。

  3. main 是图表的标题。

  4. xlab 是水平轴上的标签。

  5. ylab 是垂直轴上的标签。

  6. xlim 是用于绘图的 x 值的限制。

  7. ylim 是用于绘图的 y 值的限制。

  8. axes 表示是否应该在图上绘制两个轴。

Example

我们使用 R 环境中可用的数据集 "mtcars" 来创建一个基本的散点图。我们使用 mtcars 中的列“wt”和“mpg”。

input <- mtcars[,c('wt','mpg')]
print(head(input))

当我们执行上述代码时,会产生以下结果 -

                    wt      mpg
Mazda RX4           2.620   21.0
Mazda RX4 Wag       2.875   21.0
Datsun 710          2.320   22.8
Hornet 4 Drive      3.215   21.4
Hornet Sportabout   3.440   18.7
Valiant             3.460   18.1

Creating the Scatterplot

下面的脚本将为 wt(重量)和 mpg(每加仑英里数)之间的关系创建一个散点图。

# Get the input values.
input <- mtcars[,c('wt','mpg')]

# Give the chart file a name.
png(file = "scatterplot.png")

# Plot the chart for cars with weight between 2.5 to 5 and mileage between 15 and 30.
plot(x = input$wt,y = input$mpg,
   xlab = "Weight",
   ylab = "Milage",
   xlim = c(2.5,5),
   ylim = c(15,30),
   main = "Weight vs Milage"
)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

scatterplot

Scatterplot Matrices

当我们有超过两个变量并且我们想要找到一个变量与其余变量之间的相关性时,我们使用散点图矩阵。我们使用 pairs() 函数创建散点图矩阵。

Syntax

在 R 中创建散点图矩阵的基本语法为 −

pairs(formula, data)

以下是所用参数的描述 -

  1. formula 表示成对使用的变量序列。

  2. data 表示将从中获取变量的数据集。

Example

每个变量都与其余变量中的每个变量配对。针对每个对绘制一个散点图。

# Give the chart file a name.
png(file = "scatterplot_matrices.png")

# Plot the matrices between 4 variables giving 12 plots.

# One variable with 3 others and total 4 variables.

pairs(~wt+mpg+disp+cyl,data = mtcars,
   main = "Scatterplot Matrix")

# Save the file.
dev.off()

当执行上述代码时,我们将获得以下输出。

scatterplot matrices

R - Mean, Median and Mode

R 中的统计分析通过使用许多内置函数来执行。这些函数大多数是 R base 包的一部分。这些函数将 R 向量作为输入以及参数,并给出了结果。

我们在本章中讨论的函数是平均值、中值和众数。

Mean

它通过计算值总和并将其除以数据序列中的值数来计算。

mean() 函数用于在 R 中计算这一内容。

Syntax

在 R 中计算均值的低级语法是 −

mean(x, trim = 0, na.rm = FALSE, ...)

以下是所用参数的描述 -

  1. x 是输入矢量。

  2. trim 用于从排序后的矢量的两端丢弃一些观测。

  3. na.rm 用于从输入矢量中删除缺失值。

Example

# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find Mean.
result.mean <- mean(x)
print(result.mean)

当我们执行上述代码时,会产生以下结果 -

[1] 8.22

Applying Trim Option

如果提供了修剪参数,则矢量中的值会被排序,然后会从计算均值中删除所需数量的观测。

如果修剪 = 0.3,则会从每端删除 3 个值,以通过计算查找均值。

在这种情况下,排序后的矢量是 (−21, −5, 2, 3, 4.2, 7, 8, 12, 18, 54),并且用于计算均值的从矢量中删除的值是从左到右的 (−21、-5、2) 和从右到左的 (12、18、54)。

# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find Mean.
result.mean <-  mean(x,trim = 0.3)
print(result.mean)

当我们执行上述代码时,会产生以下结果 -

[1] 5.55

Applying NA Option

如果有缺失值,则均值函数将返回 NA。

若要从计算中删除缺失值,请使用 na.rm = TRUE。表示删除 NA 值。

# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)

# Find mean.
result.mean <-  mean(x)
print(result.mean)

# Find mean dropping NA values.
result.mean <-  mean(x,na.rm = TRUE)
print(result.mean)

当我们执行上述代码时,会产生以下结果 -

[1] NA
[1] 8.22

Median

数据系列中的最中间值称为中位数。 median() 函数用于在 R 中计算此值。

Syntax

在 R 中计算中位数的基本语法是 −

median(x, na.rm = FALSE)

以下是所用参数的描述 -

  1. x 是输入矢量。

  2. na.rm 用于从输入矢量中删除缺失值。

Example

# Create the vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)

# Find the median.
median.result <- median(x)
print(median.result)

当我们执行上述代码时,会产生以下结果 -

[1] 5.6

Mode

众数是数据集中出现次数最多的值。与均值和中位数不同,众数既可以是数字数据,也可以是字符数据。

R 没有用来计算众数的标准内置函数。因此,我们创建了一个用户函数来计算 R 中数据集的众数。此函数将矢量作为输入,并给出众数值作为输出。

Example

# Create the function.
getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

# Create the vector with numbers.
v <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)

# Calculate the mode using the user function.
result <- getmode(v)
print(result)

# Create the vector with characters.
charv <- c("o","it","the","it","it")

# Calculate the mode using the user function.
result <- getmode(charv)
print(result)

当我们执行上述代码时,会产生以下结果 -

[1] 2
[1] "it"

R - Linear Regression

回归分析是一种非常广泛使用的统计工具,可用于建立两个变量之间的关系模型。这些变量之一称为预测变量,其值是通过实验收集的。另一个变量称为响应变量,其值是从预测变量导出的。

在线性回归中,这两个变量通过一个方程相关联,其中这两个变量的指数(幂)为 1。在数学上,当作为图形绘制时,线性关系表示一条直线。任何变量的指数不等于 1 的非线性关系会形成一条曲线。

线性回归的通用数学方程为 -

y = ax + b

以下是所用参数的描述 -

  1. y 是响应变量。

  2. x 是预测变量。

  3. ab 是常数,称为系数。

Steps to Establish a Regression

回归的一个简单示例是在知道身高时预测体重。为此,我们需要身高和体重之间的关系。

创建此关系的步骤为 -

  1. 进行实验收集一组身高和相应体重的观测值。

  2. 使用 R 中的 lm() 函数创建关系模型。

  3. 从创建的模型中找出系数并利用这些系数创建数学方程

  4. 获取关系模型的摘要以了解预测中的平均误差。也称为 residuals

  5. 要预测新个体的体重,请使用 R 中的 predict() 函数。

Input Data

以下是表示观测值的样本数据 -

# Values of height
151, 174, 138, 186, 128, 136, 179, 163, 152, 131

# Values of weight.
63, 81, 56, 91, 47, 57, 76, 72, 62, 48

lm() Function

此函数创建预测变量和响应变量之间的关系模型。

Syntax

线性回归中 lm() 函数的基本语法是 -

lm(formula,data)

以下是所用参数的描述 -

  1. formula 是表示 x 和 y 之间关系的符号。

  2. data 是公式将应用到的向量。

Create Relationship Model & get the Coefficients

x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

print(relation)

当我们执行上述代码时,会产生以下结果 -

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
   -38.4551          0.6746

Get the Summary of the Relationship

x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

print(summary(relation))

当我们执行上述代码时,会产生以下结果 -

Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q     Median      3Q     Max
-6.3002    -1.6629  0.0412    1.8944  3.9775

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -38.45509    8.04901  -4.778  0.00139 **
x             0.67461    0.05191  12.997 1.16e-06 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.253 on 8 degrees of freedom
Multiple R-squared:  0.9548,    Adjusted R-squared:  0.9491
F-statistic: 168.9 on 1 and 8 DF,  p-value: 1.164e-06

predict() Function

Syntax

预测中 predict() 的基本语法是 -

predict(object, newdata)

以下是所用参数的描述 -

  1. object 是使用 lm() 函数创建的公式。

  2. newdata 是包含预测器变量的新值的向量。

Predict the weight of new persons

# The predictor vector.
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)

# The resposne vector.
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

# Find weight of a person with height 170.
a <- data.frame(x = 170)
result <-  predict(relation,a)
print(result)

当我们执行上述代码时,会产生以下结果 -

       1
76.22869

Visualize the Regression Graphically

# Create the predictor and response variable.
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
relation <- lm(y~x)

# Give the chart file a name.
png(file = "linearregression.png")

# Plot the chart.
plot(y,x,col = "blue",main = "Height & Weight Regression",
abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

linearregression

R - Multiple Regression

多元回归是线性回归在两个以上变量之间的关系方面的扩展。在简单的线性关系中,我们有一个预测变量和一个响应变量,而在多元回归中,我们有多个预测变量和一个响应变量。

多元回归的一般数学方程式为:

y = a + b1x1 + b2x2 +...bnxn

以下是所用参数的描述 -

  1. y 是响应变量。

  2. a, b1, b2&#8230;&#8203;bn 是系数。

  3. x1, x2, &#8230;&#8203;xn 是预测变量。

我们在 R 中使用 lm() 函数创建回归模型。该模型使用输入数据决定系数的值。接下来,我们可以使用这些系数来预测给定的预测变量集合的响应变量的值。

lm() Function

此函数创建预测变量和响应变量之间的关系模型。

Syntax

lm() 函数在多元回归中的基本语法是 −

lm(y ~ x1+x2+x3...,data)

以下是所用参数的描述 -

  1. formula 是表征响应变量和预测变量之间关系的符号。

  2. data 是公式将应用到的向量。

Example

Input Data

考虑 R 环境中可用的数据组 "mtcars"。它以每加仑英里 (mpg)、气缸位移 ("disp")、马力 ("hp")、汽车重量 ("wt") 和更多参数对不同的汽车型号进行比较。

该模型的目标是建立 "mpg" 作为响应变量与 "disp"、"hp" 和 "wt" 作为预测变量之间的关系。我们为此目的从 mtcars 数据集中创建这些变量的子集。

input <- mtcars[,c("mpg","disp","hp","wt")]
print(head(input))

当我们执行上述代码时,会产生以下结果 -

                   mpg   disp   hp    wt
Mazda RX4          21.0  160    110   2.620
Mazda RX4 Wag      21.0  160    110   2.875
Datsun 710         22.8  108     93   2.320
Hornet 4 Drive     21.4  258    110   3.215
Hornet Sportabout  18.7  360    175   3.440
Valiant            18.1  225    105   3.460

Create Relationship Model & get the Coefficients

input <- mtcars[,c("mpg","disp","hp","wt")]

# Create the relationship model.
model <- lm(mpg~disp+hp+wt, data = input)

# Show the model.
print(model)

# Get the Intercept and coefficients as vector elements.
cat("# # # # The Coefficient Values # # # ","\n")

a <- coef(model)[1]
print(a)

Xdisp <- coef(model)[2]
Xhp <- coef(model)[3]
Xwt <- coef(model)[4]

print(Xdisp)
print(Xhp)
print(Xwt)

当我们执行上述代码时,会产生以下结果 -

Call:
lm(formula = mpg ~ disp + hp + wt, data = input)

Coefficients:
(Intercept)         disp           hp           wt
  37.105505      -0.000937        -0.031157    -3.800891

# # # # The Coefficient Values # # #
(Intercept)
   37.10551
         disp
-0.0009370091
         hp
-0.03115655
       wt
-3.800891

Create Equation for Regression Model

基于上述截距和系数值,我们创建数学方程。

Y = a+Xdisp.x1+Xhp.x2+Xwt.x3
or
Y = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3

Apply Equation for predicting New Values

我们可以使用上面创建的回归方程来预测在提供一组新的位移、马力和重量值时行驶里程。

对于一辆位移为 221、马力为 102 且重量为 2.91 的汽车,预测的行驶里程为 −

Y = 37.15+(-0.000937)*221+(-0.0311)*102+(-3.8008)*2.91 = 22.7104

R - Logistic Regression

逻辑回归是一种回归模型,其中响应变量(因变量)具有分类值,如真/假或 0/1。它实际上测量了根据与预测变量有关的数学方程,二元响应的概率作为响应变量的值。

逻辑回归的通用数学方程为 −

y = 1/(1+e^-(a+b1x1+b2x2+b3x3+...))

以下是所用参数的描述 -

  1. y 是响应变量。

  2. x 是预测变量。

  3. ab 是作为数字常量的系数。

用于创建回归模型的函数是 glm() 函数。

Syntax

glm() 函数在逻辑回归中的基本语法为 −

glm(formula,data,family)

以下是所用参数的描述 -

  1. formula 是表示变量之间关系的符号。

  2. data 是给定这些变量值的数据集。

  3. family 为 R 对象,用于指定模型的详细信息。其值为逻辑回归的二项式。

Example

内置数据集“mtcars”描述了不同汽车型号及其各种发动机规格。“mtcars”数据集中,变速模式(自动或手动)由 am 列描述,它是一个二进制值(0 或 1)。我们可以在“am”列和其他 3 个列(hp、wt 和 cyl)之间创建逻辑回归模型。

# Select some columns form mtcars.
input <- mtcars[,c("am","cyl","hp","wt")]

print(head(input))

当我们执行上述代码时,会产生以下结果 -

                  am   cyl  hp    wt
Mazda RX4          1   6    110   2.620
Mazda RX4 Wag      1   6    110   2.875
Datsun 710         1   4     93   2.320
Hornet 4 Drive     0   6    110   3.215
Hornet Sportabout  0   8    175   3.440
Valiant            0   6    105   3.460

Create Regression Model

我们使用 glm() 函数创建回归模型并获得其摘要以进行分析。

input <- mtcars[,c("am","cyl","hp","wt")]

am.data = glm(formula = am ~ cyl + hp + wt, data = input, family = binomial)

print(summary(am.data))

当我们执行上述代码时,会产生以下结果 -

Call:
glm(formula = am ~ cyl + hp + wt, family = binomial, data = input)

Deviance Residuals:
     Min        1Q      Median        3Q       Max
-2.17272     -0.14907  -0.01464     0.14116   1.27641

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) 19.70288    8.11637   2.428   0.0152 *
cyl          0.48760    1.07162   0.455   0.6491
hp           0.03259    0.01886   1.728   0.0840 .
wt          -9.14947    4.15332  -2.203   0.0276 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 43.2297  on 31  degrees of freedom
Residual deviance:  9.8415  on 28  degrees of freedom
AIC: 17.841

Number of Fisher Scoring iterations: 8

Conclusion

在摘要中,由于变量“cyl”和“hp”最后一列中的 p 值大于 0.05,我们认为它们对变量“am”的值贡献不大。此回归模型中只有重量(wt)影响“am”值。

R - Normal Distribution

在来自独立来源的随机数据集合中,通常观察到数据的分布是正态的。这意味着,通过绘制一个图形,其中水平轴为变量值,垂直轴为值计数,我们可以得到一个钟形曲线。曲线的中心表示数据集的均值。在图形中,50% 的值位于均值的左侧,而其他 50% 位于图形右侧。在统计中,这称为正态分布。

R 具有四个内置函数用于生成正态分布。它们在下方进行了描述。

dnorm(x, mean, sd)
pnorm(x, mean, sd)
qnorm(p, mean, sd)
rnorm(n, mean, sd)

以下是上面函数中使用的参数的描述 -

  1. x 是数字向量。

  2. p 是概率向量。

  3. n 是观测数(样本量)。

  4. mean 是样本数据的均值。其默认值为 0。

  5. sd 是标准差。其默认值为 1。

dnorm()

此函数针对给定的均值和标准差提供每个点的概率分布高度。

# Create a sequence of numbers between -10 and 10 incrementing by 0.1.
x <- seq(-10, 10, by = .1)

# Choose the mean as 2.5 and standard deviation as 0.5.
y <- dnorm(x, mean = 2.5, sd = 0.5)

# Give the chart file a name.
png(file = "dnorm.png")

plot(x,y)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

dnorm

pnorm()

此函数给出了正态分布随机数小于给定数字值的概率。它也称为 “累积分布函数”。

# Create a sequence of numbers between -10 and 10 incrementing by 0.2.
x <- seq(-10,10,by = .2)

# Choose the mean as 2.5 and standard deviation as 2.
y <- pnorm(x, mean = 2.5, sd = 2)

# Give the chart file a name.
png(file = "pnorm.png")

# Plot the graph.
plot(x,y)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

pnorm

qnorm()

此函数获取概率值并给出一个其累积值与概率值匹配的数字。

# Create a sequence of probability values incrementing by 0.02.
x <- seq(0, 1, by = 0.02)

# Choose the mean as 2 and standard deviation as 3.
y <- qnorm(x, mean = 2, sd = 1)

# Give the chart file a name.
png(file = "qnorm.png")

# Plot the graph.
plot(x,y)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

qnorm

rnorm()

此函数用于生成分布呈正态分布的随机数。它以样本量作为输入并生成数量与之相等的随机数。我们绘制一个直方图来显示生成数字的分布。

# Create a sample of 50 numbers which are normally distributed.
y <- rnorm(50)

# Give the chart file a name.
png(file = "rnorm.png")

# Plot the histogram for this sample.
hist(y, main = "Normal DIstribution")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

rnorm

R - Binomial Distribution

二项分布模型用于找出某个事件在某系列实验中仅有两项可能结果的成功概率。例如,抛掷一枚硬币总是会得到正面或反面。估计二项分布期间重复抛掷一枚硬币 10 次中正好得到 3 次正面的概率。

R 有四个生成二项分布的内置函数。其描述如下。

dbinom(x, size, prob)
pbinom(x, size, prob)
qbinom(p, size, prob)
rbinom(n, size, prob)

以下是所用参数的描述 -

  1. x 是数字向量。

  2. p 是概率向量。

  3. n 是观察次数。

  4. size 是试验次数。

  5. prob 是每次试验成功的概率。

dbinom()

此函数给出了每个点的概率密度分布。

# Create a sample of 50 numbers which are incremented by 1.
x <- seq(0,50,by = 1)

# Create the binomial distribution.
y <- dbinom(x,50,0.5)

# Give the chart file a name.
png(file = "dbinom.png")

# Plot the graph for this sample.
plot(x,y)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

dbinom

pbinom()

此函数给出了事件的累积概率。它是一个表示概率的单一值。

# Probability of getting 26 or less heads from a 51 tosses of a coin.
x <- pbinom(26,51,0.5)

print(x)

当我们执行上述代码时,会产生以下结果 -

[1] 0.610116

qbinom()

此函数获取概率值并给出一个其累积值与概率值匹配的数字。

# How many heads will have a probability of 0.25 will come out when a coin
# is tossed 51 times.
x <- qbinom(0.25,51,1/2)

print(x)

当我们执行上述代码时,会产生以下结果 -

[1] 23

rbinom()

此函数从给定样本中生成给定概率所需数量的随机值。

# Find 8 random values from a sample of 150 with probability of 0.4.
x <- rbinom(8,150,.4)

print(x)

当我们执行上述代码时,会产生以下结果 -

[1] 58 61 59 66 55 60 61 67

R - Poisson Regression

泊松回归涉及响应变量为计数形式而不是分数形式的回归模型。例如,出生人数或足球比赛系列中胜利的次数。响应变量的值也遵循泊松分布。

泊松回归的通用的数学方程为 -

log(y) = a + b1x1 + b2x2 + bnxn.....

以下是所用参数的描述 -

  1. y 是响应变量。

  2. ab 是数字系数。

  3. x 是预测变量。

用于创建泊松回归模型的函数是 glm() 函数。

Syntax

glm() 函数在泊松回归中的基本语法是 -

glm(formula,data,family)

以下是上面函数中使用的参数的描述 -

  1. formula 是表示变量之间关系的符号。

  2. data 是给定这些变量值的数据集。

  3. family 是 R 对象,用于指定模型的细节。对于逻辑回归,它的值为“泊松”。

Example

我们有内置的数据集“warpbreaks”,它描述了羊毛类型(A 或 B)和张力(低、中或高)对每台织机经纱断裂次数的影响。我们不妨将“断裂”视为响应变量,它是断裂次数的计数。羊毛“类型”和“张力”被视为预测变量。

Input Data

input <- warpbreaks
print(head(input))

当我们执行上述代码时,会产生以下结果 -

      breaks   wool  tension
1     26       A     L
2     30       A     L
3     54       A     L
4     25       A     L
5     70       A     L
6     52       A     L

Create Regression Model

output <-glm(formula = breaks ~ wool+tension, data = warpbreaks,
   family = poisson)
print(summary(output))

当我们执行上述代码时,会产生以下结果 -

Call:
glm(formula = breaks ~ wool + tension, family = poisson, data = warpbreaks)

Deviance Residuals:
    Min       1Q     Median       3Q      Max
  -3.6871  -1.6503  -0.4269     1.1902   4.2616

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  3.69196    0.04541  81.302  < 2e-16 ***
woolB       -0.20599    0.05157  -3.994 6.49e-05 ***
tensionM    -0.32132    0.06027  -5.332 9.73e-08 ***
tensionH    -0.51849    0.06396  -8.107 5.21e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 297.37  on 53  degrees of freedom
Residual deviance: 210.39  on 50  degrees of freedom
AIC: 493.06

Number of Fisher Scoring iterations: 4

在摘要中,我们寻找最后一列中的 p 值是否小于 0.05,以考虑预测变量对响应变量的影响。如上所述,张力类型为 M 和 H 的 B 型羊毛对断数有影响。

R - Analysis of Covariance

我们使用回归分析来创建模型,描述预测变量的变化对响应变量造成的影响。有时,如果我们有一个具有类似于 Yes/No 或 Male/Female 等值类型的分类变量。则简单的回归分析给出分类变量的每个值的多个结果。在这样的情况下,我们能通过将其与预测变量一起使用,并比较分类变量每个级别的回归线,研究分类变量的影响。这样的分析被称为 Analysis of Covariance ,也称为 ANCOVA

Example

考虑 R 中内置的数据集 mtcars。其中我们观察到字段“am”表示传输类型(自动或手动)。它是一个具有值 0 和 1 的分类变量。除了马力(“hp”)值外,汽车每加仑英里数(mpg)值也可能依赖于此。

我们通过使用 aov() 函数研究了“am”值对“mpg”和“hp”之间回归的影响,然后使用 anova() 函数比较多个回归。

Input Data

从 mtcars 数据集中创建一个包含字段“mpg”、“hp”和“am”的数据框。在这里,我们取“mpg”为响应变量,“hp”为预测变量,“am”为分类变量。

input <- mtcars[,c("am","mpg","hp")]
print(head(input))

当我们执行上述代码时,会产生以下结果 -

                   am   mpg   hp
Mazda RX4          1    21.0  110
Mazda RX4 Wag      1    21.0  110
Datsun 710         1    22.8   93
Hornet 4 Drive     0    21.4  110
Hornet Sportabout  0    18.7  175
Valiant            0    18.1  105

ANCOVA Analysis

我们创建了一个回归模型,将“hp”作为预测变量,“mpg”作为响应变量,同时考虑“am”和“hp”之间的交互作用。

Model with interaction between categorical variable and predictor variable

# Get the dataset.
input <- mtcars

# Create the regression model.
result <- aov(mpg~hp*am,data = input)
print(summary(result))

当我们执行上述代码时,会产生以下结果 -

            Df Sum Sq Mean Sq F value   Pr(>F)
hp           1  678.4   678.4  77.391 1.50e-09 ***
am           1  202.2   202.2  23.072 4.75e-05 ***
hp:am        1    0.0     0.0   0.001    0.981
Residuals   28  245.4     8.8
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

此结果表明马力和传动类型对每加仑英里数都有显著影响,因为这两种情况下的 p 值都小于 0.05。但是,这两个变量之间的交互作用并不显着,因为 p 值大于 0.05。

Model without interaction between categorical variable and predictor variable

# Get the dataset.
input <- mtcars

# Create the regression model.
result <- aov(mpg~hp+am,data = input)
print(summary(result))

当我们执行上述代码时,会产生以下结果 -

            Df  Sum Sq  Mean Sq   F value   Pr(>F)
hp           1  678.4   678.4   80.15 7.63e-10 ***
am           1  202.2   202.2   23.89 3.46e-05 ***
Residuals   29  245.4     8.5
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

此结果表明马力和传动类型对每加仑英里数都有显著影响,因为这两种情况下的 p 值都小于 0.05。

Comparing Two Models

现在我们可以比较这两个模型,得出变量之间的交互作用是否真的无关紧要的结论。为此,我们使用 anova() 函数。

# Get the dataset.
input <- mtcars

# Create the regression models.
result1 <- aov(mpg~hp*am,data = input)
result2 <- aov(mpg~hp+am,data = input)

# Compare the two models.
print(anova(result1,result2))

当我们执行上述代码时,会产生以下结果 -

Model 1: mpg ~ hp * am
Model 2: mpg ~ hp + am
  Res.Df    RSS Df  Sum of Sq     F Pr(>F)
1     28 245.43
2     29 245.44 -1 -0.0052515 6e-04 0.9806

由于 p 值大于 0.05,我们得出结论,马力和变速箱类型之间的交互并不显着。因此,每加仑英里数在自动和手动变速模式下将以类似的方式取决于汽车的马力。

R - Time Series Analysis

时间序列是一系列数据点,其中每个数据点都与时间戳相关联。一个简单的例子是股票市场中某支股票在给定日期不同时间点的价格。另一个例子是某个地区不同月份的降雨量。R 语言使用许多函数来创建、处理和绘制时间序列数据。时间序列的数据存储在称为 time-series object 的 R 对象中。它也是一个 R 数据对象,如向量或数据框。

时间序列对象是使用 ts() 函数创建的。

Syntax

时间序列分析中 ts() 函数的基本语法为:

timeseries.object.name <-  ts(data, start, end, frequency)

以下是所用参数的描述 -

  1. data 是包含时间序列中使用值的向量或矩阵。

  2. start 指定时间序列中第一个观测值的开始时间。

  3. end 指定时间序列中最后一个观测值的结束时间。

  4. frequency 指定每个单位时间的观测值数量。

除了“data”参数之外,所有其他参数都是可选的。

Example

考虑从 2012 年 1 月开始某个地方的年降雨量详细信息。我们创建了为期 12 个月的时间序列对象并对其进行绘制。

# Get the data points in form of a R vector.
rainfall <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)

# Convert it to a time series object.
rainfall.timeseries <- ts(rainfall,start = c(2012,1),frequency = 12)

# Print the timeseries data.
print(rainfall.timeseries)

# Give the chart file a name.
png(file = "rainfall.png")

# Plot a graph of the time series.
plot(rainfall.timeseries)

# Save the file.
dev.off()

当我们执行上述代码时,它会产生以下结果和图表:

Jan    Feb    Mar    Apr    May     Jun    Jul    Aug    Sep
2012  799.0  1174.8  865.1  1334.6  635.4  918.5  685.5  998.6  784.2
        Oct    Nov    Dec
2012  985.0  882.8 1071.0

时间序列图表:

rainfall

Different Time Intervals

函数 ts() 中 frequency 参数的值决定了测量数据点的时段。12 的值表示该时间序列为 12 个月。其他值及其含义如下:

  1. frequency = 12 确定一年中每个月的点。

  2. frequency = 4 确定一年中每个季度的点。

  3. frequency = 6 确定一小时中每 10 分钟的点。

  4. frequency = 24*6 确定一天中每 10 分钟的点。

Multiple Time Series

我们通过将这两个系列合并到一个矩阵中,可以在一个图表中绘制多个时间序列。

# Get the data points in form of a R vector.
rainfall1 <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)
rainfall2 <-
           c(655,1306.9,1323.4,1172.2,562.2,824,822.4,1265.5,799.6,1105.6,1106.7,1337.8)

# Convert them to a matrix.
combined.rainfall <-  matrix(c(rainfall1,rainfall2),nrow = 12)

# Convert it to a time series object.
rainfall.timeseries <- ts(combined.rainfall,start = c(2012,1),frequency = 12)

# Print the timeseries data.
print(rainfall.timeseries)

# Give the chart file a name.
png(file = "rainfall_combined.png")

# Plot a graph of the time series.
plot(rainfall.timeseries, main = "Multiple Time Series")

# Save the file.
dev.off()

当我们执行上述代码时,它会产生以下结果和图表:

           Series 1  Series 2
Jan 2012    799.0    655.0
Feb 2012   1174.8   1306.9
Mar 2012    865.1   1323.4
Apr 2012   1334.6   1172.2
May 2012    635.4    562.2
Jun 2012    918.5    824.0
Jul 2012    685.5    822.4
Aug 2012    998.6   1265.5
Sep 2012    784.2    799.6
Oct 2012    985.0   1105.6
Nov 2012    882.8   1106.7
Dec 2012   1071.0   1337.8

多时间序列图表 -

rainfall combined

R - Nonlinear Least Square

当对回归分析建模真实世界数据时,我们观察到这种情况很少,即模型的方程式是给出线性图的线性方程式。大多数情况下,实际世界数据的模型方程涉及高次数学函数,如 3 的指数或正弦函数。在这种情况下,模型图给出曲线而不是线。线性回归和非线性回归的目标都是调整模型参数的值,以找到最接近您的数据线或曲线。通过发现这些值,我们将能够以良好的准确度估计响应变量。

在最小二乘回归中,我们建立了一个回归模型,其中不同点从回归曲线的垂直距离的平方和最小化。我们通常从一个定义的模型开始,并为系数假定一些值。然后,我们应用 R 的 nls() 函数来获取更准确的值以及置信区间。

Syntax

在 R 中创建非线性最小二乘测试的基本语法为 −

nls(formula, data, start)

以下是所用参数的描述 -

  1. formula 是一个非线性模型公式,包括变量和参数。

  2. data 是用于评估公式中变量的数据框。

  3. start 是起始估计的命名列表或命名数字向量。

Example

我们将考虑具有其系数初始值假设的非线性模型。接下来,我们将看到这些假设值的置信区间是什么,以便我们可以判断这些值如何很好地适应模型。

因此,让我们考虑以下用于此目的的方程式 −

a = b1*x^2+b2

让我们假设初始系数为 1 和 3,并将这些值代入 nls() 函数。

xvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21)
yvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58)

# Give the chart file a name.
png(file = "nls.png")


# Plot these values.
plot(xvalues,yvalues)


# Take the assumed values and fit into the model.
model <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3))

# Plot the chart with new data by fitting it to a prediction from 100 data points.
new.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100))
lines(new.data$xvalues,predict(model,newdata = new.data))

# Save the file.
dev.off()

# Get the sum of the squared residuals.
print(sum(resid(model)^2))

# Get the confidence intervals on the chosen values of the coefficients.
print(confint(model))

当我们执行上述代码时,会产生以下结果 -

[1] 1.081935
Waiting for profiling to be done...
       2.5%    97.5%
b1 1.137708 1.253135
b2 1.497364 2.496484
nls

我们可以得出结论,b1 的值更接近 1,而 b2 的值更接近 2 而不是 3。

R - Decision Tree

Decision tree is a graph to represent choices and their results in form of a tree. The nodes in the graph represent an event or choice and the edges of the graph represent the decision rules or conditions. It is mostly used in Machine Learning and Data Mining applications using R.

Examples of use of decision tress is − predicting an email as spam or not spam, predicting of a tumor is cancerous or predicting a loan as a good or bad credit risk based on the factors in each of these. Generally, a model is created with observed data also called training data. Then a set of validation data is used to verify and improve the model. R has packages which are used to create and visualize decision trees. For new set of predictor variable, we use this model to arrive at a decision on the category (yes/No, spam/not spam) of the data.

The R package "party" is used to create decision trees.

Install R Package

在 R 控制台中使用以下命令安装包。还需要安装相关包(如果存在)。

install.packages("party")

The package "party" has the function ctree() which is used to create and analyze decison tree.

Syntax

The basic syntax for creating a decision tree in R is −

ctree(formula, data)

以下是所用参数的描述 -

  1. formula 是描述预测变量和响应变量的公式。

  2. data 是所用数据集的名称。

Input Data

We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone’s readingSkills if we know the variables "age","shoesize","score" and whether the person is a native speaker or not.

以下是示例数据。

# Load the party package. It will automatically load other
# dependent packages.
library(party)

# Print some records from data set readingSkills.
print(head(readingSkills))

当我们执行上述代码时,它会产生以下结果和图表:

  nativeSpeaker   age   shoeSize      score
1           yes     5   24.83189   32.29385
2           yes     6   25.95238   36.63105
3            no    11   30.42170   49.60593
4           yes     7   28.66450   40.28456
5           yes    11   31.88207   55.46085
6           yes    10   30.07843   52.83124
Loading required package: methods
Loading required package: grid
...............................
...............................

Example

We will use the ctree() function to create the decision tree and see its graph.

# Load the party package. It will automatically load other
# dependent packages.
library(party)

# Create the input data frame.
input.dat <- readingSkills[c(1:105),]

# Give the chart file a name.
png(file = "decision_tree.png")

# Create the tree.
  output.tree <- ctree(
  nativeSpeaker ~ age + shoeSize + score,
  data = input.dat)

# Plot the tree.
plot(output.tree)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 -

null device
          1
Loading required package: methods
Loading required package: grid
Loading required package: mvtnorm
Loading required package: modeltools
Loading required package: stats4
Loading required package: strucchange
Loading required package: zoo

Attaching package: ‘zoo’

The following objects are masked from ‘package:base’:

   as.Date, as.Date.numeric

Loading required package: sandwich
decision tree

Conclusion

From the decision tree shown above we can conclude that anyone whose readingSkills score is less than 38.3 and age is more than 6 is not a native Speaker.

R - Random Forest

在随机森林方法中,会创建大量决策树。每个观察都会传入到每个决策树。每个观察的最常见结果将用作最终输出。将新观察传入到所有树,并针对每个分类模型进行多数表决。

对在创建树时未使用的案例进行误差估计。这称为 OOB (Out-of-bag) 误差估计,以百分比表示。

R 包 "randomForest" 用于创建随机森林。

Install R Package

在 R 控制台中使用以下命令安装包。还需要安装相关包(如果存在)。

install.packages("randomForest)

“randomForest”包具有 randomForest() 函数,该函数用于创建和分析随机森林。

Syntax

在 R 中创建随机森林的基本语法为 −

randomForest(formula, data)

以下是所用参数的描述 -

  1. formula 是描述预测变量和响应变量的公式。

  2. data 是所用数据集的名称。

Input Data

我们将使用 R 中名为 readingSkills 的内置数据集来创建决策树。它描述了如果我们知道变量“年龄”、“鞋码”、“分数”以及该人是否是母语人士,则某个人的阅读技能得分。

以下是示例数据。

# Load the party package. It will automatically load other
# required packages.
library(party)

# Print some records from data set readingSkills.
print(head(readingSkills))

当我们执行上述代码时,它会产生以下结果和图表:

  nativeSpeaker   age   shoeSize      score
1           yes     5   24.83189   32.29385
2           yes     6   25.95238   36.63105
3            no    11   30.42170   49.60593
4           yes     7   28.66450   40.28456
5           yes    11   31.88207   55.46085
6           yes    10   30.07843   52.83124
Loading required package: methods
Loading required package: grid
...............................
...............................

Example

我们将使用 randomForest() 函数来创建决策树并查看其图表。

# Load the party package. It will automatically load other
# required packages.
library(party)
library(randomForest)

# Create the forest.
output.forest <- randomForest(nativeSpeaker ~ age + shoeSize + score,
           data = readingSkills)

# View the forest results.
print(output.forest)

# Importance of each predictor.
print(importance(fit,type = 2))

当我们执行上述代码时,会产生以下结果 -

Call:
 randomForest(formula = nativeSpeaker ~ age + shoeSize + score,
                 data = readingSkills)
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 1

        OOB estimate of  error rate: 1%
Confusion matrix:
    no yes class.error
no  99   1        0.01
yes  1  99        0.01
         MeanDecreaseGini
age              13.95406
shoeSize         18.91006
score            56.73051

Conclusion

从上面显示的随机森林中,我们可以得出结论,鞋码和分数是决定某人是否是母语人士的重要因素。此外,该模型只有 1% 的错误,这意味着我们可以预测 99% 的准确性。

R - Survival Analysis

生存分析用于预测特定事件发生的的时间。它也称为失效时间分析或死亡时间分析。例如,预测患有癌症的人的存活天数或预测机械系统何时失效。

名为 survival 的 R 包用于执行生存分析。此包包含函数 Surv() ,该函数将输入数据作为 R 公式,并在选定的变量中创建生存对象以进行分析。然后,我们使用函数 survfit() 为分析创建绘图。

Install Package

install.packages("survival")

Syntax

在 R 中创建生存分析的基本语法是 −

Surv(time,event)
survfit(formula)

以下是所用参数的描述 -

  1. time 是直到事件发生时的后续时间。

  2. event 表示预期事件发生的状态。

  3. formula 是预测变量之间的关系。

Example

我们将在上述安装的生存包中考虑名为“pbc”的数据集。它描述了患有原发性胆汁性肝硬化 (PBC) 的人的生存数据点。在数据集中存在的众多列中,我们主要关注字段“时间”和“状态”。时间表示患者登记到患者接受肝移植或死亡之间发生的事件的时间,以较早者为准。

# Load the library.
library("survival")

# Print first few rows.
print(head(pbc))

当我们执行上述代码时,它会产生以下结果和图表:

  id time status trt      age sex ascites hepato spiders edema bili chol
1  1  400      2   1 58.76523   f       1      1       1   1.0 14.5  261
2  2 4500      0   1 56.44627   f       0      1       1   0.0  1.1  302
3  3 1012      2   1 70.07255   m       0      0       0   0.5  1.4  176
4  4 1925      2   1 54.74059   f       0      1       1   0.5  1.8  244
5  5 1504      1   2 38.10541   f       0      1       1   0.0  3.4  279
6  6 2503      2   2 66.25873   f       0      1       0   0.0  0.8  248
  albumin copper alk.phos    ast trig platelet protime stage
1    2.60    156   1718.0 137.95  172      190    12.2     4
2    4.14     54   7394.8 113.52   88      221    10.6     3
3    3.48    210    516.0  96.10   55      151    12.0     4
4    2.54     64   6121.8  60.63   92      183    10.3     4
5    3.53    143    671.0 113.15   72      136    10.9     3
6    3.98     50    944.0  93.00   63       NA    11.0     3

从以上数据中,我们考虑时间和状态来进行分析。

Applying Surv() and survfit() Function

现在,我们开始将 Surv() 函数应用到以上数据集,并创建一个用于显示趋势的绘图。

# Load the library.
library("survival")

# Create the survival object.
survfit(Surv(pbc$time,pbc$status == 2)~1)

# Give the chart file a name.
png(file = "survival.png")

# Plot the graph.
plot(survfit(Surv(pbc$time,pbc$status == 2)~1))

# Save the file.
dev.off()

当我们执行上述代码时,它会产生以下结果和图表:

Call: survfit(formula = Surv(pbc$time, pbc$status == 2) ~ 1)

      n  events  median 0.95LCL 0.95UCL
    418     161    3395    3090    3853
survival

上图中的趋势帮助我们预测在一定数量的日期结束时存活的概率。

R - Chi Square Test

Chi-Square test 是一种统计方法,用于确定两个分类变量之间是否存在显着相关性。这两个变量都应该来自同一人群,并且都应该是分类变量,例如是/否、男/女、红/绿等。

例如,我们可以创建一个包含人们冰淇淋购买模式的数据集,并尝试将人的性别与其偏好的冰淇淋口味相关联。如果找到相关性,我们可以了解来访者的性别数量,以此来规划合适的口味库存。

Syntax

用于执行卡方检验的函数是 chisq.test()

在 R 中创建卡方检验的基本语法为:

chisq.test(data)

以下是所用参数的描述 -

  1. data 是数据的表格形式,包含观察值中变量的计数值。

Example

我们将采用“MASS”库中的 Cars93 数据,其中表示 1993 年不同汽车型号的销售额。

library("MASS")
print(str(Cars93))

当我们执行上述代码时,会产生以下结果 -

'data.frame':   93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ...

以上结果显示数据集具有许多因子变量,这些变量可视为分类变量。对于我们的模型,我们将考虑变量“AirBags”和“Type”。在这里,我们旨在找出销售的汽车类型与其拥有的安全气囊类型之间的任何显着相关性。如果观察到相关性,我们可以估计哪种类型的汽车可以更好地销售哪种类型的安全气囊。

# Load the library.
library("MASS")

# Create a data frame from the main data set.
car.data <- data.frame(Cars93$AirBags, Cars93$Type)

# Create a table with the needed variables.
car.data = table(Cars93$AirBags, Cars93$Type)
print(car.data)

# Perform the Chi-Square test.
print(chisq.test(car.data))

当我们执行上述代码时,会产生以下结果 -

                     Compact Large Midsize Small Sporty Van
  Driver & Passenger       2     4       7     0      3   0
  Driver only              9     7      11     5      8   3
  None                     5     0       4    16      3   6

         Pearson's Chi-squared test

data:  car.data
X-squared = 33.001, df = 10, p-value = 0.0002723

Warning message:
In chisq.test(car.data) : Chi-squared approximation may be incorrect

Conclusion

结果显示 p 值小于 0.05,表示存在显著相关性。