Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in R, passing a dataframe and a column name [duplicate]

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?

like image 246
jpsfer Avatar asked Sep 05 '11 15:09

jpsfer


People also ask

How do you repeat a column in a Dataframe in R?

First of all, create a data frame. Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.

Can you have duplicate column names in R?

By default, R does not allow duplicate column names in a data frame.

How do I find duplicate columns in R?

So, how do you find and eliminate duplicated columns? The easiest way to remove duplicated columns from a data frame is by using the duplicated() function. This function returns a logical vector indicating which column(s) appear more than once in a data frame.

How can you retrieve the names of rows and columns of a data frame in R?

To find the column names and row names in an R data frame based on a condition, we can use row. names and colnames function.


1 Answers

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
like image 72
Andrie Avatar answered Sep 25 '22 01:09

Andrie