1. 基本语法
print()
、cat()
:打印输出
#
:单行注释
if(FALSE){code block}
:多行注释
2. 数据类型
class()
:查看数据类型
2.1 基本数据类型
基本数据类型 | 示例 |
---|---|
逻辑值(logical) | 真:TRUE 、T ,假:FALSE 、F |
数字(numeric) | 123、5 |
整型(integer) | 2L、34L |
复数(complex) | 3+2i |
字符(character) | 'good' |
2.2 向量Vector
c()
函数创建向量。
注意:必须保证元素类型相同,否则会默认进行类型转换。
> x <- c(1, 2)
> class(x)
[1] "numeric"
> x <- c('s')
> class(x)
[1] "character"
> x <- c(1, 2, 's')
> class(x)
[1] "character"
2.3 列表List
列表可以包含许多不同类型的元素,如向量、函数、嵌套列表。
注意:[]
与[[]]
的区别。[]
取出来的仍是一个列表,[[]]
取出来的是本身的数据类型。
> list1 <- list(c(2,3), 21, 's', sin) # 分别包含列表、数字、字符、函数
> class(list1)
[1] "list"
> list1[1] # 取出来的仍是一个列表
[[1]]
[1] 2 3
> list1[[1]] # 取出来的是子列表中的元素
[1] 2 3
> class(list1[1])
[1] "list"
> class(list1[[1]])
[1] "numeric"
> list1[[2]]
[1] 21
> list1[2] + 2
Error in list1[2] + 2 : non-numeric argument to binary operator
> list1[[2]] + 2
[1] 23
> list1[[4]]
function (x) .Primitive("sin")
> class(list1[[4]])
[1] "function"
2.4 矩阵Matrix
矩阵是二维数据集,它可以使用矩阵函数的向量输入创建。
byrow
参数决定元素存放的顺序。
> M <- matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
> M
[,1] [,2] [,3]
[1,] "a" "a" "b"
[2,] "c" "b" "a"
> M[,1] # 取出第一列数据
[1] "a" "c"
> M[1,] # 取出第一行数据
[1] "a" "a" "b"
> M[2,1] # 取出单个元素
[1] "c"
2.5 数组Array
利用数组可以创建任意维度的数据。
> array1 <- array(c('green','yellow'), dim=c(3,3,2))
> array1
, , 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"
2.6 因子Factor
因子是使用向量创建的对象。它将向量与向量中元素的不同值一起存储为标签。 标签是字符类型。 它们在统计建模中非常有用。
使用factor()
函数创建因子。nlevels
函数给出级别计数。
> apple_colors <- c('green','green','yellow','red','red','red','green')
> factor_apple <- factor(apple_colors)
> factor_apple
[1] green green yellow red red red green
Levels: green red yellow
> nlevels(factor_apple)
[1] 3
2.7 数据框Data Frame
表格数据对象。每列可以包含不同的数据类型。 第一列可以是数字,而第二列可以是字符,第三列可以是逻辑的。 它是等长度的向量的列表。
使用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)
)
> BMI
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26
# 获取第二列
> BMI[2]
height
1 152.0
2 171.5
3 165.0
# 获取第一行
> BMI[1,]
gender height weight Age
1 Male 152 81 42
# 获取第一列数据,类型为DataFrame
> BMI[1]
gender
1 Male
2 Male
3 Female
> class(BMI[1])
[1] "data.frame"
# 获取第一列,并将其转换为factor类型
> BMI[,1]
[1] Male Male Female
Levels: Female Male
# 获取第一个元素,转换为factor类型
> BMI[1,1]
[1] Male
Levels: Female Male
# 获取第二列,不改变数据类型
> BMI[2]
height
1 152.0
2 171.5
3 165.0
# 获取第二列,改变数据类型
> BMI[,2]
[1] 152.0 171.5 165.0
# 根据列的名称获取factor类型数据
data_frame$col_name