5 对象类型

https://www.runoob.com/r/r-data-types.html

5.1 向量(Vector)

a <- c(3, 4)
a
## [1] 3 4
a[2]
## [1] 4

5.2 因子(factor)

x <- c("male", "female", "male", "female", "female")
sex <- factor(x)  # 字符型向量转换成因子
sex
## [1] male   female male   female female
## Levels: female male

5.3 矩阵(matrix)

v = c(1, 2, 3, 4, 5, 6)  # 这是向量
matrix(v, 2, 3)  # 竖二横三,竖着填充
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
m1 <- matrix(v, 2, 3, byrow = TRUE)  # 竖二横三,横着填充
m1
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
m1[1, 3]  # 第一行第三列
## [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
m1["a", ]
## x y z 
## 1 2 3

apply() 函数可以将矩阵的每一行或每一列当作向量来进行操作:

A = matrix(c(1, 3, 2, 4), 2, 2)
apply(A, 1, sum)  # 第一行第二行分别求和
## [1] 3 7
apply(A, 2, sum)  # 按列求和
## [1] 4 6

5.4 数据框(data.frame)

与矩阵的区别在于数据框的不同列可以放不同的数据类型

table <- data.frame(name = c("Jack", "Mary"), id = c("001", "002"), salary = c(1000,
    2000))
print(table)
##   name  id salary
## 1 Jack 001   1000
## 2 Mary 002   2000
table[, 1:2]
##   name  id
## 1 Jack 001
## 2 Mary 002

5.5 数组(array)

三维的

vector1 <- c(5, 9, 3)
vector2 <- c(10, 11, 12, 13, 14, 15)
# 创建数组
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

5.6 列表(list)

啥都能装。如果想放到一起的一堆元素有字符串有数字就可以用list而不用向量。

list_data <- list("runoob", "google", c(11, 22, 33), 123, 51.23, 119.1)
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_data <- list(c("Google", "Runoob", "Taobao"), matrix(c(1, 2, 3, 4,
    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

列表转换成向量

# 创建列表
list1 <- list(1:5)
print(list1)
## [[1]]
## [1] 1 2 3 4 5
list2 <- list(10:14)
print(list2)
## [[1]]
## [1] 10 11 12 13 14
# 转换为向量
v1 <- unlist(list1)
v2 <- unlist(list2)

print(v1)
## [1] 1 2 3 4 5
print(v2)
## [1] 10 11 12 13 14
# 两个向量相加
result <- v1 + v2
print(result)
## [1] 11 13 15 17 19