如何在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
相关产品推荐
相关产品推荐

