5 对象类型
https://www.runoob.com/r/r-data-types.html
5.2 因子(factor)
<- c("male", "female", "male", "female", "female")
x <- factor(x) # 字符型向量转换成因子
sex sex
## [1] male female male female female
## Levels: female male
5.3 矩阵(matrix)
= c(1, 2, 3, 4, 5, 6) # 这是向量
v matrix(v, 2, 3) # 竖二横三,竖着填充
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
<- matrix(v, 2, 3, byrow = TRUE) # 竖二横三,横着填充
m1 m1
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
1, 3] # 第一行第三列 m1[
## [1] 3
colnames(m1) = c("x", "y", "z")
rownames(m1) = c("a", "b")
m1
## x y z
## a 1 2 3
## b 4 5 6
"a", ] m1[
## x y z
## 1 2 3
apply() 函数可以将矩阵的每一行或每一列当作向量来进行操作:
= matrix(c(1, 3, 2, 4), 2, 2)
A apply(A, 1, sum) # 第一行第二行分别求和
## [1] 3 7
apply(A, 2, sum) # 按列求和
## [1] 4 6
5.4 数据框(data.frame)
与矩阵的区别在于数据框的不同列可以放不同的数据类型
<- data.frame(name = c("Jack", "Mary"), id = c("001", "002"), salary = c(1000,
table 2000))
print(table)
## name id salary
## 1 Jack 001 1000
## 2 Mary 002 2000
1:2] table[,
## name id
## 1 Jack 001
## 2 Mary 002
5.5 数组(array)
三维的
<- c(5, 9, 3)
vector1 <- c(10, 11, 12, 13, 14, 15)
vector2 # 创建数组
<- array(c(vector1, vector2), dim = c(3, 3, 2))
result 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
5.6 列表(list)
啥都能装。如果想放到一起的一堆元素有字符串有数字就可以用list而不用向量。
<- list("runoob", "google", c(11, 22, 33), 123, 51.23, 119.1)
list_data print(list_data)
## [[1]]
## [1] "runoob"
##
## [[2]]
## [1] "google"
##
## [[3]]
## [1] 11 22 33
##
## [[4]]
## [1] 123
##
## [[5]]
## [1] 51.23
##
## [[6]]
## [1] 119.1
命名
# 列表包含向量、矩阵、列表
<- list(c("Google", "Runoob", "Taobao"), matrix(c(1, 2, 3, 4,
list_data 5, 6), nrow = 2), list("runoob", 12.3))
# 给列表元素设置名字
names(list_data) <- c("Sites", "Numbers", "Lists")
# 显示列表
print(list_data)
## $Sites
## [1] "Google" "Runoob" "Taobao"
##
## $Numbers
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
##
## $Lists
## $Lists[[1]]
## [1] "runoob"
##
## $Lists[[2]]
## [1] 12.3
列表转换成向量
# 创建列表
<- list(1:5)
list1 print(list1)
## [[1]]
## [1] 1 2 3 4 5
<- list(10:14)
list2 print(list2)
## [[1]]
## [1] 10 11 12 13 14
# 转换为向量
<- unlist(list1)
v1 <- unlist(list2)
v2
print(v1)
## [1] 1 2 3 4 5
print(v2)
## [1] 10 11 12 13 14
# 两个向量相加
<- v1 + v2
result print(result)
## [1] 11 13 15 17 19