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?
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.
By default, R does not allow duplicate column names in a data frame.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With