美文网首页
R语言:基础篇

R语言:基础篇

作者: JackHCC | 来源:发表于2020-02-26 19:23 被阅读0次

    一.R环境设置

    尝试在线环境

    你真的不需要设置自己的环境来开始学习R编程语言。 原因很简单,我们已经在线设置了R编程环境,以便您可以在进行理论工作的同时在线编译和执行所有可用的示例。 这给你对你正在阅读的信心,并用不同的选项检查结果。 随意修改任何示例并在线执行。
    实例:

    # Print Hello World. 
    print("Hello World") 
     
    # Add two numbers. 
    print(23.9 + 11.6)
    

    Windows安装

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

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

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

    Linux安装

    R语言适用于多版本的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语言 基本语法

    命令提示符

    如果你已经配置好R语言环境,那么你只需要按一下的命令便可轻易开启命令提示符

    $ R
    

    这将启动R语言解释器,你会得到一个提示 > 在那里你可以开始输入你的程序,具体如下。

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

    在这里,第一个语句先定义一个字符串变量myString,并将“Hello,World!”赋值其中,第二句则使用print()语句将变量myString的内容进行打印。

    脚本文件

    通常,您将通过在脚本文件中编写程序来执行编程,然后在命令提示符下使用R解释器(称为Rscript)来执行这些脚本。 所以让我们开始在一个命名为test.R的文本文件中编写下面的代码

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

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

    $ Rscript test.R 
    

    当我们运行上面的程序,它产生以下结果。

    [1] "Hello, World!"
    

    注释

    注释能帮助您解释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)
    

    虽然上面的注释将由R解释器执行,但它们不会干扰您的实际程序。 但是你必须为内容加上单引号或双引号。

    三.数据结构

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

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

    与其他编程语言(如C中的C和java)相反,变量不会声明为某种数据类型。 变量分配有R对象,R对象的数据类型变为变量的数据类型。尽管有很多类型的R对象,但经常使用的是:

    • 矢量
    • 列表
    • 矩阵
    • 数组
    • 因子
    • 数据帧
      这些对象中最简单的是向量对象,并且这些原子向量有六种数据类型,也称为六类向量。 其他R对象建立在原子向量之上。
    • Logical(逻辑型):TRUE, FALSE
    • Numeric(数字) 12.3,5,999
    • Integer(整型) 2L,34L,0L
    • Complex(复合型) 3 + 2i
    • Character(字符) 'a' , '"good", "TRUE", '23.4'
    • Raw(原型) "Hello" 被存储为 48 65 6c 6c 6f
      在R编程中,非常基本的数据类型是称为向量的R对象,其保存如上所示的不同类的元素。 请注意,在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    yellow green 
    Levels: green red yellow
    # applying the nlevels function we can know the number of distinct values
    [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语言中的变量可以存储原子向量,原子向量组或许多Robject的组合。 有效的变量名称由字母,数字和点或下划线字符组成。 变量名以字母或不以数字后跟的点开头。
    注:有字母,数字,点和下划线,其中只能字母开头

    变量赋值

    可以使用向左,向右和等于运算符来为变量分配值。 可以使用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 ,"
    ")
    cat ("var.2 is ", var.2 ,"
    ")
    cat ("var.3 is ", var.3 ,"
    ")
    

    当我们执行上面的代码,它产生以下结果 -

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

    注 - 向量c(TRUE,1)具有逻辑和数值类的混合。 因此,逻辑类强制转换为数字类,使TRUE为1。

    变量的数据类型

    在R语言中,变量本身没有声明任何数据类型,而是获取分配给它的R - 对象的数据类型。 所以R称为动态类型语言,这意味着我们可以在程序中使用同一个变量时,一次又一次地更改变量的数据类型。

    var_x <- "Hello"
    cat("The class of var_x is ",class(var_x),"
    ")
    
    var_x <- 34.5
    cat("  Now the class of var_x is ",class(var_x),"
    ")
    
    var_x <- 27L
    cat("   Next the class of var_x becomes ",class(var_x),"
    ")
    

    当我们执行上面的代码,它产生以下结果 -

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

    查找变量

    要知道工作空间中当前可用的所有变量,我们使用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" 
    

    注意 - 它是一个示例输出,取决于在您的环境中声明的变量。
    ls()函数可以使用模式来匹配变量名。
    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"    
    

    以点(.)开头的变量被隐藏,它们可以使用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"  
    

    删除变量

    可以使用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语言具有丰富的内置运算符,并提供以下类型的运算符。

    运算符的类型

    R语言中拥有如下几种运算符类型:

    • 算术运算符
    • 关系运算符
    • 逻辑运算符
    • 赋值运算符
    • 其他运算符
    • 算术运算符
      下表显示了R语言支持的算术运算符。 操作符对向量的每个元素起作用。
      除了加减乘除
    • %% 两个向量求余
    • %/% 两个向量相除求商
    • ^ 将第二向量作为第一向量的指数

    关系运算符

    即大于小于等于以及不等于

    逻辑运算符

    下表显示了R语言支持的逻辑运算符。 它只适用于逻辑,数字或复杂类型的向量。 所有大于1的数字被认为是逻辑值TRUE。
    将第一向量的每个元素与第二向量的相应元素进行比较。 比较的结果是布尔值。

    • & 它被称为元素逻辑AND运算符。 它将第一向量的每个元素与第二向量的相应元素组合,并且如果两个元素都为TRUE,则给出输出TRUE。
    • | 它被称为元素逻辑或运算符。 它将第一向量的每个元素与第二向量的相应元素组合,并且如果元素为真,则给出输出TRUE。
    • ! 它被称为逻辑非运算符。 取得向量的每个元素,并给出相反的逻辑值。
      逻辑运算符&&和|| 只考虑向量的第一个元素,给出单个元素的向量作为输出。
    • && 称为逻辑AND运算符。 取两个向量的第一个元素,并且只有两个都为TRUE时才给出TRUE。
    • || 称为逻辑OR运算符。 取两个向量的第一个元素,如果其中一个为TRUE,则给出TRUE。

    赋值运算符

    这些运算符用于向向量赋值。

    • <− or = or <<− 称为左分配
    • -> or ->> 称为右分配

    其他运算符

    这些运算符用于特定目的,而不是一般的数学或逻辑计算。

    • : 冒号运算符。 它为向量按顺序创建一系列数字。
    • %in% 此运算符用于标识元素是否属于向量。
    • %*% 此运算符用于将矩阵与其转置相乘。

    六.决策

    决策结构要求程序员指定要由程序评估或测试的一个或多个条件,以及如果条件被确定为真则要执行的一个或多个语句,如果条件为假则执行其他语句。

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

    做决定

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

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

    if语句后面可以有一个可选的else语句,当布尔表达式为false时执行。

    switch语句允许根据值列表测试变量的相等性。

    七.包

    R语言的包是R函数,编译代码和样本数据的集合。 它们存储在R语言环境中名为“library”的目录下。 默认情况下,R语言在安装期间安装一组软件包。 随后添加更多包,当它们用于某些特定目的时。 当我们启动R语言控制台时,默认情况下只有默认包可用。 已经安装的其他软件包必须显式加载以供将要使用它们的R语言程序使用。

    所有可用的R语言包都列在R语言的包
    下面是用于检查,验证和使用R包的命令列表。

    检查可用R语言的包

    获取包含R包的库位置

    .libPaths()
    

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

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

    获取已安装的所有软件包列表

    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
    

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

    search()
    

    当我们执行上述代码时,它产生了以下结果。它会根据你的个人电脑的本地设置而异。

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

    安装一个新的软件包

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

    直接从CRAN安装

    以下命令直接从CRAN网页获取软件包,并将软件包安装在R环境中。 可能会提示您选择最近的镜像。 根据您的位置选择一个。

    # Install the package named "XML".
     install.packages("XML")
    
    手动安装包

    转到链接R Packages下载所需的包。 将包作为.zip文件保存在本地系统中的适当位置。
    现在您可以运行以下命令在R环境中安装此软件包。

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

    装载包到库中

    在包可以在代码中使用之前,必须将其加载到当前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编程语言提供以下种类的循环来处理循环需求。 单击以下链接以检查其详细信息。

    多次执行一系列语句,并简化管理循环变量的代码。

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

    像while语句,不同之处在于它测试在循环体的端部的条件。

    循环控制语句

    循环控制语句从其正常序列改变执行。 当执行离开作用域时,在该作用域中创建的所有自动对象都将被销毁。
    R语言支持以下控制语句。 单击以下链接以检查其详细信息。

    终止循环语句,并将执行转移到循环后立即执行的语句。

    next语句模拟R语言switch语句的行为。

    十.数据重塑

    R语言中的数据重塑是关于改变数据被组织成行和列的方式。 大多数时间R语言中的数据处理是通过将输入数据作为数据帧来完成的。 很容易从数据帧的行和列中提取数据,但是在某些情况下,我们需要的数据帧格式与我们接收数据帧的格式不同。 R语言具有许多功能,在数据帧中拆分,合并和将行更改为列,反之亦然。

    于数据帧中加入列和行

    我们可以使用cbind()函数连接多个向量来创建数据帧。 此外,我们可以使用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
    ") 
    
    # 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
    ") 
    
    # 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
    ") 
    
    # 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
    

    合并数据帧

    我们可以使用merge()函数合并两个数据帧。 数据帧必须具有相同的列名称,在其上进行合并。

    在下面的例子中,我们考虑图书馆名称“MASS”中有关Pima Indian Women的糖尿病的数据集。 我们基于血压(“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
    

    melt()拆分数据和cast()数据重构

    R语言编程的一个最有趣的方面是关于在多个步骤中改变数据的形状以获得期望的形状。 用于执行此操作的函数称为melt()和cast()。

    我们考虑称为船舶的数据集称为“MASS”。

    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()拆分数据

    现在我们拆分数据进行重组,将除类型和年份以外的所有列转换为多行展示。

    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()重构数据

    我们可以将被拆分的数据转换为一种新形式,使用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语言具有大量内置函数,用户可以创建自己的函数。

    在R语言中,函数是一个对象,因此R语言解释器能够将控制传递给函数,以及函数完成动作所需的参数。

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

    函数定义

    使用关键字函数创建R语言的函数。 R语言的函数定义的基本语法如下

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

    函数组件

    函数的不同部分 -

    • 函数名称 -这是函数的实际名称。 它作为具有此名称的对象存储在R环境中。

    • 参数 -参数是一个占位符。 当函数被调用时,你传递一个值到参数。 参数是可选的; 也就是说,一个函数可能不包含参数。 参数也可以有默认值。

    • 函数体 -函数体包含定义函数的功能的语句集合。

    • 返回值 -函数的返回值是要评估的函数体中的最后一个表达式。
      R语言有许多内置函数,可以在程序中直接调用而无需先定义它们。我们还可以创建和使用我们自己的函数,称为用户定义的函数。

    内置功能

    内置函数的简单示例是seq(),mean(),max(),sum(x)和paste(...)等。它们由用户编写的程序直接调用。 您可以参考最广泛使用的R函数。

    # 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
    

    用户定义的函数

    我们可以在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)
       }
    }   
    

    调用函数

    # 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
    

    调用没有参数的函数

    # 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
    

    使用参数值调用函数(按位置和名称)
    函数调用的参数可以按照函数中定义的顺序提供,也可以以不同的顺序提供,但分配给参数的名称。

    # 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
    

    使用默认参数调用函数
    我们可以在函数定义中定义参数的值,并调用函数而不提供任何参数以获取默认结果。 但是我们也可以通过提供参数的新值来获得非默认结果来调用这样的函数。

    # 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
    

    功能的延迟计算
    对函数的参数进行延迟评估,这意味着它们只有在函数体需要时才进行评估。

    # 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语言中的单引号或双引号对中写入的任何值都被视为字符串.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"
    
    无效字符串的示例
    e <- 'Mixed quotes" 
    print(e)
    
    f <- 'Single quote ' inside single quote'
    print(f)
    
    g <- "Double quotes " inside double quotes"
    print(g)
    

    当我们运行脚本失败给下面的结果。

    ...: unexpected INCOMPLETE_STRING
    
    .... unexpected symbol 
    1: f <- 'Single quote ' inside
    
    unexpected symbol
    1: g <- "Double quotes " inside
    

    字符串操作

    连接字符串 - paste()函数

    R 语言中的许多字符串使用paste()函数组合。它可以采取任何数量的参数组合在一起。

    语法

    对于粘贴功能的基本语法是 -

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

    以下是所使用的参数的说明 -

    • ...表示要组合的任意数量的自变量。

    • 九月表示参数之间的任何分隔符。它是可选的。

    • collapse用于消除两个字符串之间的空格。但不是一个字符串的两个字内的空间。

    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? "
    
    格式化数字和字符串 - format()函数

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

    语法

    格式化函数的基本语法是 -

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

    以下是所使用的参数的描述 -

    • X是向量输入。

    • 数字是显示的总位数。

    • nsmall是小数点右边的最小位数。

    • 科学设置为TRUE以显示科学记数法。

    • 宽度指示通过在开始处填充空白来显示的最小宽度。

    • 理由是字符串向左,右或中心的显示。

    # 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  "
    
    计算字符串中的字符数 - nchar()函数

    此函数计算字符串中包含空格的字符数。

    语法

    nchar()函数的基本语法是 -

    nchar(x)
    以下是所使用的参数的描述 -

    • X是向量输入。

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

    当我们执行上面的代码,它产生以下结果 -

    [1] 30
    
    更改案例 - toupper()和tolower()函数

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

    语法

    toupper()和tolower()函数的基本语法是 -

    toupper(x)
    tolower(x)
    

    以下是所使用的参数的描述 -

    • X是向量输入。

    # 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"
    
    提取字符串的一部分 - substring()函数

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

    语法

    substring()函数的基本语法是 -

    substring(x,first,last)
    

    以下是所使用的参数的描述 -

    • X是字符向量输入。

    • 首先是要提取的第一个字符的位置。

    • 最后是要提取的最后一个字符的位置。

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

    当我们执行上面的代码,它产生以下结果 -

    [1] "act"
    

    十三.向量

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

    创建向量

    单元素向量

    即使在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
    
    多元素向量

    对数值数据使用冒号运算符

    # 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
    
    使用sequence (Seq.)序列运算符
    # 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
    
    使用C()函数

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

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

    当我们执行上面的代码,它产生以下结果 -

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

    访问向量元素

    使用索引访问向量的元素。 []括号用于建立索引。 索引从位置1开始。在索引中给出负值会丢弃来自result.TRUE,FALSE或0和1的元素,也可用于索引。

    # 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"
    

    向量操作

    向量运算

    可以添加,减去,相乘或相除两个相同长度的向量,将结果作为向量输出。

    # 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 substraction.
    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
    
    向量元素回收

    如果我们对不等长的两个向量应用算术运算,则较短向量的元素被循环以完成操作。

    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
    

    向量元素排序

    向量中的元素可以使用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语言对象,它包含不同类型的元素,如数字,字符串,向量和其中的另一个列表。列表还可以包含矩阵或函数作为其元素。列表是使用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
    

    命名列表元素

    列表元素可以给出名称,并且可以使用这些名称访问它们。

    # 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
    

    访问列表元素

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

    我们继续使用在上面的例子列表 -

    # 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
    

    操控列表元素

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

    # 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"
    
    $
    NULL
    
    $`A Inner list`
    [1] "updated element"
    

    合并列表

    通过将所有列表放在一个列表()函数中,您可以将许多列表合并到一个列表中。

    # 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"
    

    将列表转换为向量

    列表可以转换为向量,使得向量的元素可以用于进一步的操作。可以在将列表转换为向量之后应用对向量的所有算术运算。要做这个转换,我们使用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对象。 它们包含相同原子类型的元素。 虽然我们可以创建一个只包含字符或只包含逻辑值的矩阵,但它们没有太多用处。 我们使用包含数字元素的矩阵用于数学计算。

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

    语法

    在R语言中创建矩阵的基本语法是 -

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

    以下是所使用的参数的说明 -

    • 数据是成为矩阵的数据元素的输入向量。

    • nrow是要创建的行数。

    • ncol是要创建的列数。

    • byrow是一个逻辑线索。 如果为TRUE,则输入向量元素按行排列。

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

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

    # 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
    

    访问矩阵的元素

    可以通过使用元素的列和行索引来访问矩阵的元素。 我们考虑上面的矩阵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 
    

    矩阵计算

    使用R运算符对矩阵执行各种数学运算。 操作的结果也是一个矩阵。
    对于操作中涉及的矩阵,维度(行数和列数)应该相同。

    矩阵加法和减法
    # 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","
    ")
    print(result)
    
    # Subtract the matrices
    result <- matrix1 - matrix2
    cat("Result of subtraction","
    ")
    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
    
    矩阵乘法和除法
    # 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","
    ")
    print(result)
    
    # Divide the matrices
    result <- matrix1 / matrix2
    cat("Result of division","
    ")
    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数据对象。例如 - 如果我们创建一个维度(2,3,4)的数组,则它创造4个矩形矩阵,每个矩阵具有2行和3列数组只能存储数据类型。
    使用array()函数创建数组。它使用向量作为输入,并使用dim参数中的值创建数组。

    以下示例创建一个由两个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
    

    命名列和行

    我们可以使用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
    

    访问数组元素

    # 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
    

    操作数组元素

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

    # 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
    

    跨数组元素的计算

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

    语法

    apply(x, margin, fun)
    

    以下是所使用的参数的说明 -

    • X是一个数组。

    • 保证金是所使用的数据集的名称。

    • 有趣的是要应用于数组元素的函数。


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

    # 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
    

    十七.因子

    因子是用于对数据进行分类并将其存储为级别的数据对象。 它们可以存储字符串和整数。 它们在具有有限数量的唯一值的列中很有用。 像“男性”,“女性”和True,False等。它们在统计建模的数据分析中很有用。
    使用factor()函数通过将向量作为输入创建因子。

    # 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
    

    数据帧的因子

    在创建具有文本数据列的任何数据框时,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
    

    更改级别顺序

    可以通过使用新的等级次序再次应用因子函数来改变因子中的等级的顺序。

    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
    

    生成因子级别

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

    语法

    gl(n, k, labels)
    

    以下是所使用的参数的说明 -

    • n是给出级数的整数。

    • k是给出复制数目的整数。

    • labels是所得因子水平的标签向量。

    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
    

    十八.数据帧

    数据帧是表或二维阵列状结构,其中每一列包含一个变量的值,并且每一行包含来自每一列的一组值。
    以下是数据帧的特性。

    • 列名称应为非空。
    • 行名称应该是唯一的。
    • 存储在数据帧中的数据可以是数字,因子或字符类型。
    • 每个列应包含相同数量的数据项。

    创建数据帧

    # 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
    

    获取数据帧的结构

    通过使用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()函数获取数据的统计摘要和性质。

    # 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 
    

    从数据帧提取数据

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

    # 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
    

    用第2和第4列提取第3和第5行

    # 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
    

    扩展数据帧

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

    添加列

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

    # 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
    

    添加行

    要将更多行永久添加到现有数据帧,我们需要引入与现有数据帧相同结构的新行,并使用rbind()函数。
    在下面的示例中,我们创建一个包含新行的数据帧,并将其与现有数据帧合并以创建最终数据帧。

    # 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语言——进阶篇

    相关文章

      网友评论

          本文标题:R语言:基础篇

          本文链接:https://www.haomeiwen.com/subject/vdbichtx.html