R代码学习----dplyr 包提供的“列选择函数”

 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值