12

Possible Duplicate:
Pass a data.frame column name to a function

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)
}

Output:

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

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?

Community
  • 1
  • 1
jpsfer
  • 594
  • 3
  • 7
  • 18

1 Answers1

19

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

Sample data:

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

Function:

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

Results:

>  my.function(dat, "b" )
  b
1 D
2 E
3 F
>  my.function(dat, "c" )
  c
1 7
2 8
3 9
Andrie
  • 176,377
  • 47
  • 447
  • 496