簡體   English   中英

如何在計算每個組的平均值時刪除 ddply 中的第 5 個和第 95 個百分位值

[英]How to remove 5th and 95th percentile values in ddply while calculating mean for each group

我有一個大型數據集,每個物種都有幾個特征值。 我想計算每個值的性狀平均值,不包括第 5 個百分位和第 95 個百分位。 我正在使用 ddply function 但無法做到這一點。 非常感謝任何幫助。

塊引用

這是計算修剪均值的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM