Cybernetic
Cybernetic

Reputation: 13334

Passing in column names to a function that runs another function in R

I am using the dplyr package to run an eggregation across a dataframe. For example I can pass my data frame in along with the 2 columns I want to aggregate by (Col_1, Col_2) and the column that actually gets aggregated (Col_to_Agg).

agg_frame <- dcast(setDT(data_frame), Col_1+Col_2~Col_to_Agg, length)

If I have this method inside a custom function, how can I pass in Col_1, Col2 and Col_to_Agg? It doesn't work if I just pass in those columns as names.

In other words I want to do this:

aggregate <- function(data_frame, Col_1, Col_2, Col_to_Agg) {

    agg_frame <- dcast(setDT(data_frame), Col_1+Col_2~Col_to_Agg, length)
    return(agg_frame)

}

Upvotes: 0

Views: 29

Answers (1)

TheComeOnMan
TheComeOnMan

Reputation: 12875

as.formula(paste(Col_1,'+',Col_2,'~',Col_to_Agg))

Upvotes: 1

Related Questions