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

R语言咨询:无需重复添加data$前缀从数据集取列构建数据框的方法

R语言省略data$前缀构建数据框的可行方法

方法1:base R原生with()函数(最安全,优先推荐)

直接用with()指定默认引用的数据集,运行结束后自动释放环境,不会产生全局变量污染:

df <- with(data, data_frame(
  Name,
  classification,
  HP,
  Weight,
  Height,
  Att,
  Def,
  Spe,
  Spa,
  Spd,
  Type_1,
  Type_2,
  Abilities,
  Generation,
  Legendary,
  Catch_Rate
))

方法2:tidyverse生态select()函数(效率最高)

如果你用tidyverse系列工具,直接按列名筛选即可,不用逐个手动列出生成:

library(dplyr)
df <- data %>% 
  select(Name, classification, HP, Weight, Height, Att, Def, Spe, Spa, Spd, Type_1, Type_2, Abilities, Generation, Legendary, Catch_Rate)

如果你需要的就是data的全部列,直接赋值即可,不需要额外写代码:

df <- data

方法3:attach()函数(不推荐日常使用)

该方法会将数据集挂载到全局搜索路径,容易和后续同名变量冲突,临时使用后必须及时卸载:

attach(data)
df <- data_frame(
  Name,
  classification,
  HP,
  Weight,
  Height,
  Att,
  Def,
  Spe,
  Spa,
  Spd,
  Type_1,
  Type_2,
  Abilities,
  Generation,
  Legendary,
  Catch_Rate
)
detach(data) # 必须执行,清理挂载的数据集

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:01