You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重定义R语言base::mean()函数以集成is.finite()功能,实现NA、NaN和Inf值的自动剔除

Solution: Custom Mean Function for tabular() That Excludes NA, NaN, and Inf

Got it, let's tweak your mean function to handle all three problematic values (NA, NaN, Inf) in one go. Here's the adjusted code:

Mean.new <- function(x) {
  # Filter to keep only finite values (automatically excludes NA, NaN, Inf)
  valid_values <- x[is.finite(x)]
  # Calculate mean of the cleaned subset
  base::mean(valid_values)
}

How this works:

  • The is.finite() function checks each element in your vector: it returns TRUE only for real numbers (so it rejects NA, NaN, and Inf all at once).
  • We use this check to subset your input x down to just valid numerical values, then compute the mean on that filtered set.
  • Unlike relying solely on na.rm=TRUE, this approach covers all three edge cases without needing extra conditional checks.

Test it to confirm:

Let's run a quick example to make sure it behaves as expected:

test_data <- c(5, 10, NA, NaN, Inf, 15)
Mean.new(test_data) # Should return (5+10+15)/3 = 10

This will give you the mean of only the valid observations, exactly what you need for your tabular() table.

内容的提问来源于stack exchange,提问作者corkinabottle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 08:38:12