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

如何基于另一数据框的列名范围筛选生成新的DataFrame

错误原因排查

  1. filter()是dplyr中用于筛选行的函数,不支持列筛选逻辑,所以第一种写法完全不符合需求
  2. 第二种select()写法缺失数据框入参,且判断列名匹配的逻辑没有正确传递给select(),因此无法执行

正确实现方式

方案1:dplyr(tidyverse生态)

library(dplyr)
# 取两个数据框的公共列名
common_cols <- intersect(names(df1), names(df2))
# 生成df3:df1仅保留公共列
df3 <- df1 %>% select(all_of(common_cols))
# 生成df4:df2仅保留公共列
df4 <- df2 %>% select(all_of(common_cols))

注:加all_of()是为了避免高版本dplyr的环境变量检索警告,属于规范写法。

方案2:纯基础R实现,无需加载任何包

common_cols <- intersect(names(df1), names(df2))
df3 <- df1[, common_cols]
df4 <- df2[, common_cols]

如果不需要提前存储公共列名,也可以直接写成一行:

df3 <- df1[, names(df1) %in% names(df2)]
df4 <- df2[, names(df2) %in% names(df1)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:45:08