Advertisement

R语言基本知识梳理

阅读量:

与多数编程语言相似,在学习R之前掌握C语言的基础上会觉得这部分内容相对容易掌握。本节仅对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对象非常多但是经常使用矢量、列表、矩阵、数组、因子、数据帧。

向量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

阵列有任何维度

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

该系统通过整合存储向量及其不同元素的值作为标签,并确保这些标签始终表示为字符类型。通过调用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

变量

赋值=

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

print(ls())

List the variables starting with the pattern "var".

print(ls(pattern = "var"))

删除变量 rm()函数

运算符

%% 两个向量求余
%/% 两个向量相除求商

安装库文件

为在R中加载新库提供了两种可用的解决方案。其中一种方式是通过官方渠道进行安装;另一种方式则是先下载至本地电脑后再进行手动安装。

install.packages("Package Name")

Install the package named "XML".

install.packages("XML")

https://cran.r-project.org/web/packages/available_packages_by_name.html

将包放入库中:

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

数据重塑

通过cbind()函数连接多个向量可以构建数据框架;同时我们也可以利用rbind()函数将两个数据集进行结合。

我们可以通过merge()函数将两个数据框架进行融合。只有当这两个表格拥有相同的字段名时才能完成这种操作。

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

函数

字符串

  • 字符串两端必须使用相同类型的括弧(双括弧或单括弧),避免混用形式。
    • 双括弧可以在由单括弧包围的内容周围应用。
    • 单括弧可以在由双括弧包围的内容周围应用。
    • 不建议在相同类型起止标记内部再嵌入相同类型的标记。
    • 同理适用于单括弧的情形。

连接字符串 - paste()函数

格式化数字和字符串 - format()函数

计算字符串中的字符数 - nchar()函数

更改字符串大小写 toupper()和tolower()函数

提取字符串的一部分 - substring()函数

Extract characters from 5th to 7th position.

result <- substring("Extract", 5, 7)

print(result)

[1] "act"

向量(加减乘除 排序)

数值型与matlab一样用冒号

序列用seq()

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()

s <- c('apple','red',5,TRUE)

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

列表

列表可以转成向量用unlist()

矩阵

matrix()创建矩阵matrix(data, nrow, ncol, byrow, dimnames)

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

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

nrow是要创建的行数。

ncol是要创建的列数。

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

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

数组

通过向量作为输入,并指定维度参数的值来构建多维数据结构。

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

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])

因子

factor() 转换为因子类型,is.factor()查看是否是因子。

例如数据帧的因子

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

可以改变因子的级别顺序

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 West North

用gl()生成因子级别

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

获取数据帧的结构

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

数据框中的数据摘要

Print the summary.

print(summary(emp.data))

emp_id emp_name salary start_date

  1. :1 Length:5 :515.2 :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

  1. :5 :843.2 :2015-03-27

从数据帧中提取数据

Extract Specific columns.

result <- data.frame(emp.dataemp_name,emp.datasalary) 提取特定列

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

提取特定行特定列

Extract first two rows.

result <- emp.data[1:2,]

print(result)

Extract 3rd and 5th row with 2nd and 4th column.

result <- emp.data[c(3,5),c(2,4)]

print(result)

扩展数据帧

扩展列:

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

扩展行:创建新的数据帧即可

全部评论 (0)

还没有任何评论哟~