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