【问题标题】:How to remove 5th and 95th percentile values in ddply while calculating mean for each group如何在计算每个组的平均值时删除 ddply 中的第 5 个和第 95 个百分位值
【发布时间】:2021-02-07 12:22:37
【问题描述】:

我有一个大型数据集,其中包含每个物种的多个特征值。我想计算每个值的特征平均值,不包括第 5 个百分位和第 95 个百分位。我正在使用 ddply 功能,但无法做到这一点。非常感谢任何帮助。

【问题讨论】:

  • Base R 的均值函数:mean(x, trim = 0.05, na.rm = TRUE)

标签: r dplyr outliers quantile


【解决方案1】:

这是一个函数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], ...)
}

现在mutate具有按species分组后的函数的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)

【讨论】:

  • 感谢您的回复。但是,我的数据集中有 NA,上面的代码给了我一个错误。
  • @Gull用na.rm = TRUE调用函数。
【解决方案2】:

带有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))

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 2017-09-15
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多