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

如何在R语言中根据前期输入指定后续脚本引用的列?

解决R语言中通过字符串变量提取数据框列的问题

你的代码报错原因是df$eval(targetcolumn)的写法错误,$运算符后需要直接指定列名,而你这里试图调用df$eval这个不存在的函数,因此触发报错:Error: attempt to apply non-function(中文翻译:尝试应用非函数)。

以下是几种正确实现需求的方法:

  • 方法一:使用方括号索引
df = data.frame(column1 = c(1,2,3,4,5), column2 = c('a','b','c','d','e'))
targetcolumn = "column1"
df[, targetcolumn]
  • 方法二:使用双括号索引(推荐,避免列名匹配歧义)
df = data.frame(column1 = c(1,2,3,4,5), column2 = c('a','b','c','d','e'))
targetcolumn = "column1"
df[[targetcolumn]]
  • 方法三:结合get()函数使用
df = data.frame(column1 = c(1,2,3,4,5), column2 = c('a','b','c','d','e'))
targetcolumn = "column1"
get(targetcolumn, envir = df)
# 或者用with简化
with(df, get(targetcolumn))

以上三种方法都能得到你预期的结果:1,2,3,4,5。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:46:59