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

在R语言中如何根据逻辑向量筛选保留数据框的指定列?

筛选数据框中符合逻辑向量条件的列

步骤1:加载数据和逻辑向量

先把逻辑向量和数据框导入R环境:

# 定义逻辑向量
keep_cols <- c(Adipocytes = TRUE, B.cells = TRUE, Basophils = FALSE, CD4..memory.T.cells = TRUE, 
CD4..naive.T.cells = TRUE, CD4..T.cells = FALSE, CD4..Tcm = TRUE, 
CD4..Tem = TRUE, CD8..naive.T.cells = FALSE, CD8..T.cells = TRUE, 
CD8..Tcm = TRUE, Class.switched.memory.B.cells = TRUE, DC = TRUE, 
Endothelial.cells = FALSE, Eosinophils = TRUE, Epithelial.cells = FALSE, 
Fibroblasts = TRUE, Hepatocytes = TRUE, ly.Endothelial.cells = TRUE, 
Macrophages = FALSE, Macrophages.M1 = TRUE, Macrophages.M2 = TRUE, 
Mast.cells = TRUE, Melanocytes = TRUE, Memory.B.cells = TRUE, 
Monocytes = FALSE, mv.Endothelial.cells = TRUE, naive.B.cells = TRUE, 
Neutrophils = TRUE, NK.cells = TRUE, pDC = TRUE, Pericytes = TRUE, 
Plasma.cells = TRUE, pro.B.cells = TRUE, Tgd.cells = TRUE, Th1.cells = FALSE, 
Th2.cells = TRUE, Tregs = FALSE)

# 加载数据框
df <- structure(list(response = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("NoResponse", "Response"), class = "factor"), 
    Adipocytes = c(0.0147750026478847, 0.0147750026478847, 0.0147750026478847, 
    0.0212089093123119, 0.0710538305419062, 0.0147750026478847, 
    0.0147750026478847), B.cells = c(0.0771628600461939, 0.0348430059727367, 
    0.166843196901955, 0.029029065282152, 0.0289092657550142, 
    0.0091727181061411, 0.0545426703298063), Basophils = c(0.123412405513611, 
    0.229980789620818, 0.710327302827785, 0.110317426229336, 
    0.593651555059932, 0.171672288243263, 0.16957000805118), 
    CD4..memory.T.cells = c(0.053430101401256, 0.00519336879475164, 
    0.00519336879475164, 0.0135894934563294, 0.00519336879475164, 
    0.00519336879475164, 0.0187854542183181), CD4..naive.T.cells = c(0.0198799983437911, 
    0.0198799983437911, 0.0198799983437911, 0.0198799983437911, 
    0.0198799983437911, 0.0198799983437911, 0.0198799983437911
    ), CD4..T.cells = c(0.0308423390003806, -0.000280618433405845, 
    -0.000280618433405845, -0.000280618433405845, -0.000280618433405845, 
    -0.000280618433405845, 0.0119164432522563)), row.names = c("Pt1", 
"Pt10", "Pt103", "Pt106", "Pt11", "Pt17", "Pt2"), class = "data.frame")

步骤2:筛选符合条件的列

从逻辑向量中提取值为TRUE的列名,再匹配数据框中存在的列,最后保留response列和这些符合条件的特征列:

# 获取逻辑向量中为TRUE的列名
true_cols <- names(keep_cols[keep_cols == TRUE])

# 只保留数据框中实际存在的符合条件的列
existing_true_cols <- intersect(true_cols, colnames(df))

# 生成筛选后的数据框
filtered_df <- df[, c("response", existing_true_cols)]

结果说明

运行上述代码后,filtered_df会保留:

  • 原始数据框中的response列
  • 所有在逻辑向量中标记为TRUE且存在于原始数据框的特征列(即Adipocytes、B.cells、CD4..memory.T.cells、CD4..naive.T.cells)

内容的提问来源于stack exchange,提问作者Programming Noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 07:24:12