梳理 R 的向量、矩阵、数组、列表、数据框和因子等核心数据结构及其索引与处理方式。
# 1. 向量
- 构造:
c() ;序列 1:5 、 seq() ;重复 rep() ;混合类型转字符。 - 索引:正负下标、区间、逻辑、
which/which.max/which.min 。 - 运算与汇总:
sqrt/sum/mean/var/sd/min/max/range/rev/sort/order/rank 。
1 2 3 4
| f <- seq(1, 10) f[c(3, 5, 8)] f[-c(3, 5, 8)] f[f > 5]
|
# 2. 矩阵与数组
- 创建:
matrix(data, nrow, ncol, byrow=FALSE, dimnames=...) ; cbind/rbind 合并。 - 索引:
m[row, col] ;负下标排除。 - 多维数组:
array(data, dim = c(r, c, k)) 。
1 2 3
| m <- matrix(1:20, nrow = 5, ncol = 4) m[2, 3]; m[2, ]; m[, 3]; m[2, -3] array(1:24, dim = c(3, 4, 2))
|
# 3. 数据框
- 创建 / 转换:
data.frame() ; as.data.frame(matrix/list) ;检测 is.data.frame 。 - 索引:
df[rows, cols] , $ / [[ ]] 取列。 - 修改:
colnames/row.names <- ; with(df, ...) 计算新列; apply/lapply/sapply 汇总。 - 取子集:
subset(df, 条件, select=...) 。 - 因子:
cut() 分箱, factor(..., ordered=TRUE) 。
1 2 3
| df <- data.frame(Name=c("Alice","Bob","Charlie"), Age=c(25,30,22)) df$BMI <- with(df, Age/10) subset(df, Age > 23, select = c(Name, BMI))
|
# 4. 列表
1 2 3 4
| subject <- c("Math", "Reading") student <- c("John", "Peter") list_one <- list(subjectNames = subject, studentNames = student) score <- matrix(1:4, nrow = 2, dimnames = list_one)
|
# 5. 字符串与正则
- 提取与长度:
substr/substring , nchar/nzchar , str_extract(_all) 。 - 拼接:
paste/paste0 ;替换: chartr/sub/gsub/str_replace(_all) 。 - 正则:
grep 家族演示 ^ $ . [] [^] .* ? * + () | - 。
1 2 3 4 5
| str <- "Hello, world!" substr(str, 1, 5) shopping <- c("apples x4", "bag of flour") str_extract(shopping, "[a-z]+") grep("^t", c("The","take","away"), value = TRUE)
|