[英]How to remove 5th and 95th percentile values in ddply while calculating mean for each group
這是計算修剪均值的 function mean2
。
mean2 <- function(x, na.rm = FALSE, probs = c(0.05, 0.95), ...){
if(na.rm) x <- x[!is.na(x)]
qq <- quantile(x, probs = probs)
keep <- x > qq[1] & x < qq[2]
mean(x[keep], ...)
}
現在在按species
分組后用 function mutate
data.frame。
library(dplyr)
df %>%
group_by(species) %>%
mutate(mean = mean2(trait))
測試數據創建代碼
set.seed(1234)
species <- sample(LETTERS[1:3], 20, TRUE)
trait <- sample(2:8, 20, TRUE)
trait[sample(20, 3)] <- sample(50:60, 3)
trait[sample(20, 1)] <- -2
df <- data.frame(species, trait)
使用for
循環:
means = numeric()
for(i in df$Species){
x = df$Trait[which(df$Species==i)]
means[i] = mean(x[which(x<=quantile(x,0.95) & x>=quantile(x,0.05))])
}
}
使用的虛擬數據:
df = data.frame(
Species = sample(rep(LETTERS[1:5],8), 40),
Trait = rnorm(40, 5, 3))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.