0

My df looks like this:

library(data.table)
df <- data.table(id = c(1,1,1,2,2), 
             starts = c(0,0,6,0,9), 
             ends = c(0,6,10,9,20))

I want to create a function which serves to create a data table with a new column containing the mean:

mean <- function(df, col_name){
library(data.table)

a <- data.table(

mean_df = df[col_name != 0, mean(col_name)]

)
return(a)
}

Then when I run the function

mean(df, "starts")

This gives me the error:

 Error in data.table(mean = df[col_name != 0, mean(col_name)]) : 
    argument "col_name" is missing, with no default 

I'm not sure what I'm doing wrong - I tried get() and substitute() to pass the column name but I'm not sure if I'm doing it correctly.

Any help is appreciated!

EDIT1: Editted name of column to be created in function

ynitSed
  • 145
  • 8
  • 3
    you are overwriting the mean function with a new function called mean, then trying to call the original mean function inside your function...its best not to create functions with the same name as base R stuff – morgan121 Mar 01 '19 at 02:55
  • 1
    maybe `meanfun <- function(df, col_name){ df[abs(get(col_name)) > 0, mean(get(col_name))] } meanfun(df, "starts")` – chinsoon12 Mar 01 '19 at 02:56

1 Answers1

1

I think using get() like so is pretty standard:

my_mean <- function(data, col_name) {
  data[get(col_name) != 0, mean(get(col_name))]
} 

my_mean(data = df, col_name = "starts")
[1] 7.5

BTW. it's a very bad idea to name your new function mean() since it will replace the base function.

s_baldur
  • 29,441
  • 4
  • 36
  • 69