I want to use a vectorized conditional average (when using ddply
and transform
) meaning an average of entries that pass a certain condition. I came up with this but am wondering if it can be implemented using built-in functions or a popular package?
mean.conditional <- function(x, cond, zero = 0) {
filter <- cond(x)
return(sum(ifelse(filter, x, zero)) / sum(filter))
}
alternatively, the following function is probably even cleaner:
mean.conditional <- function(x, filter) {
return(sum(ifelse(filter, x, 0)) / sum(filter))
没有内置函数,但这可以做到:
sum(x*filter) / sum(filter)
mean(x[cond(x)])
做你想要的吗?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.