You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中一行代码从data.frame提取符合条件的值到向量

一行代码从data.frame提取特定值到向量(以mtcars为例)

基础R实现

直接通过逻辑索引筛选,是最简洁的写法:

cyl6.disp <- mtcars$disp[mtcars$cyl == 6]

执行后即可得到目标向量:c(160.0, 160.0, 258.0, 225.0, 167.6, 167.6, 145.0)

也可以用subset()函数,逻辑表述更直观:

cyl6.disp <- subset(mtcars, cyl == 6, select = disp)$disp

tidyverse(dplyr包)实现

如果习惯用tidyverse生态的管道语法,可组合filter()和pull()完成:

library(dplyr)
cyl6.disp <- mtcars %>% filter(cyl == 6) %>% pull(disp)

内容的提问来源于stack exchange,提问作者Sylvia Rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:14:50