R 里,select() 是 dplyr 包提供的“列选择函数”,语法非常灵活。
1. 基本语法
select(.data, ...)
# `.data`:数据框 / tibble
#`...`:列名、位置、逻辑表达式或 helper 函数(见下文)
2. 最常用 4 种写法
文本信息表
目的 |
示例 |
说明 |
按列名 |
`select(data, ID, type)` |
只保留 ID、type |
排除列 |
`select(data, -ID, -type)` |
去掉 ID、type |
连续列 |
`select(data, ID:last_col())` |
从 ID 到最后一列 |
指定位置 |
`select(data, 3:10)` |
第 3–10 列 |
3. 辅助函数(helper)
函数 |
作用 |
示例 |
`starts_with()` |
以某前缀开头 |
`select(df, starts_with("m/z"))` |
`ends_with()` |
以某后缀结尾 |
`select(df, ends_with(".mzML"))` |
`contains()` |
包含某字符串 |
`select(df, contains("VIP"))` |
`matches()` |
正则匹配 |
`select(df, matches("^m\\d+$"))` |
`everything()` |
全部列(常用于调整列顺序) |
`select(df, type, everything())` |
4. 与 `as.matrix()` 联用示例
# 去掉前两列后转矩阵
meta.mat <- dat %>% select(-1, -2) %>% as.matrix()
# 或保留第3列以后
meta.mat <- dat %>% select(3:ncol(.)) %>% as.matrix()
5. 常见坑提醒
(1) 一旦用 `column_to_rownames()` 把列变成行名,这些列就不再存在于数据框,此时再用 `select(-ID, -type)` 就会报错。
(2)如果列里有非数值列,`as.matrix()` 会把所有列变成字符矩阵,后续数值运算会出错 → 先用 `select()` 去掉非数值列,或 `mutate(across(where(is.character), as.numeric))` 转换。
(3)报错Error in select...参数没有用...:需要加前缀dplyr::select
参考https://zhuanlan.zhihu.com/p/381296115