0

I'm attempting to create a function that uses dplyr inside of it. However, I can't quite seem to figure out how to select a column from a data.frame. I'm trying to do something like this example:

test_df <- data.frame(A=1:30)
my_function <- function(x, var){
    x %>%
        summarize(my_mean = mean(var))
}
my_function(test_df, "A")

Which produces this error:

Warning message: In mean.default("A") : argument is not numeric or logical: returning NA.

Any ideas how to fix this?

Alex
  • 1,997
  • 1
  • 15
  • 32

1 Answers1

1

Probably the easiest way to fix this, is to subset from .:

my_function <- function(x, var){
    x %>%
        summarize(my_mean = mean(.[[var]]))
}
jeremycg
  • 24,657
  • 5
  • 63
  • 74