如何重定义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 returnsTRUEonly for real numbers (so it rejects NA, NaN, and Inf all at once). - We use this check to subset your input
xdown 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
相关产品推荐
相关产品推荐

