I have this dataset:
toy <- cbind(ID = c(1:10),
group1 = sample(1:3, 10, replace = TRUE),
group2 = sample(1:3, 10, replace = TRUE),
value = rnorm(1:10))
ID group1 group2 value
[1,] 1 1 2 -0.32903883
[2,] 2 3 3 0.06923648
[3,] 3 1 1 0.09690423
[4,] 4 1 3 0.29003439
[5,] 5 3 2 -0.74667894
[6,] 6 1 2 -0.84689639
[7,] 7 3 3 1.19707766
[8,] 8 1 3 -0.54862736
[9,] 9 2 2 0.30304570
[10,] 10 1 3 -0.05697053
I want to write a function with two arguments: dataframe
, focal.var
.
the function takes a dataframe
, groups it by a group1
and takes the mean of focal.var
. I do not know how to pass the column names to mean()
function below. I tried this:
focal <- function(dataset, focal.var){
df <- dataset %>%
group_by(group1) %>%
mutate(FV_ft = mean(focal.var))
return(df)
after calling my function:
focal(dataset = toy, focal.var = "value")
produces this error:
argument is not numeric or logical: returning NA