I want to calculate the mean value of the column inside the function. Let's try in this example:
test = data.frame(value = c(231,43,12,342,123,543,56,122,321,222),
category = c("A","B","A","B","A","A","A","B","B","B"))
fun <- function(AorB) {
example <- test %>%
filter(category == AorB) %>%
select(value)
## %>% (here I want to add mean calculation)
## mean() (it is not possible)
## sum()/nrow (it is not possible)
}
solve <- fun("A")
The whole problem with 'mean()' and 'sum()/nrow()' is that the 'mean()' and 'nrow()' need to specify the data.frame. All calculations are inside the function so I can't specify the data.frame like this:
mean(example$value)
Per Sin's suggestion in the comments...
I think you need to use:
example <- test %>% filter(category == AorB) %>% summarise( mean = mean(value))
For dplyr, you need to call (and name) those summary functions within the summarise() function.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments