R中的函数,传递数据框和列名 [英] Function in R, passing a dataframe and a column name

查看:58
本文介绍了R中的函数,传递数据框和列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
将data.frame列名传递给函数

我试图在R中创建一个函数,其中在输入之间有数据框和列名.该代码将是这样的:

I am trying to create a function in R where between the inputs there is dataframe and a column name. The code would be something like this:

DT_CAP_COLUMN  <- function(input_table,output_table,column_name,
                           cap_function,Parameter){
  input_table$column_name
  (...)
  return(1)
}

输出:

DT_CAP_COLUMN(churn_3,churn_4,'VOICE_REVENUE','STD',3)
input_table$column_name is NA

我认为问题是无法识别 input_table $ column_name . input_table churn_3 ,但是 input_table $ column_name 返回 column_name .

I think the problem is that input_table$column_name is not recognized. input_table is churn_3 but input_table$column_name returns column_name not found.

是否有必要执行此操作而不必使用按引用传递程序包或将传递环境用作变量?

Is there anyway to do this without having to use pass-by-references packages or passing environments as variables?

推荐答案

您可以使用方括号索引间接引用data.frame中的列:

You can indirectly reference a column in a data.frame by using square bracket indexing:

样本数据:

 dat <- data.frame(
     a = letters[1:3],
     b = LETTERS[4:6],
     c = 7:9
 )

功能:

 my.function <- function(data, col){
   data[, col]
 }

结果:

>  my.function(dat, "b" )
  b
1 D
2 E
3 F
>  my.function(dat, "c" )
  c
1 7
2 8
3 9

这篇关于R中的函数,传递数据框和列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆