R 找到三个数字中最接近的平均值-代码优化

R 找到三个数字中最接近的平均值-代码优化,r,R,这可能看起来微不足道,但我有一个代码,可以在一组三个数字中找到最接近的两个数字的平均值。因此,有5个例子: x1 <- c(1,5,7) x2 <- c(NA,2,3) x3 <- c(2,6,4) x4 <- c(1,NA,NA) x5 <- c(1,3,1) 分别。基本上,找到最接近的2个数字,然后求平均值,计算NA和ties 此代码是一个怪物: x <-x[!is.na(x)] x <-x[order(x)] y <-ifelse(leng

这可能看起来微不足道,但我有一个代码,可以在一组三个数字中找到最接近的两个数字的平均值。因此,有5个例子:

x1 <- c(1,5,7)
x2 <- c(NA,2,3)
x3 <- c(2,6,4)
x4 <- c(1,NA,NA)
x5 <- c(1,3,1)
分别。基本上,找到最接近的2个数字,然后求平均值,计算NA和ties

此代码是一个怪物:

x <-x[!is.na(x)]
x <-x[order(x)]
y <-ifelse(length(x) == 1, x, 
      ifelse(length(x) == 2, mean(x), 
        ifelse(length(x) == 3, 
          ifelse(abs(x[1] - x[2]) == abs(x[2] - x[3]), mean(x), 
            ifelse(abs(x[1] - x[2]) > abs(x[2] - x[3]), mean(x[2:3]),
              ifelse(abs(x[1] - x[2]) < abs(x[2] - x[3]), mean(x[1:2]), 
     "error"))), NA)))

x我们使用
“list”
“default”
方法定义S3泛型


“default”
方法获取一个向量并对其进行排序(这也会删除NA值),然后如果剩下的长度是yes,但OP不是这样做的:
abs(x[1]-x[2])==abs(x[2]-x[3]),则表示(x)
OK。修改了。
x <-x[!is.na(x)]
x <-x[order(x)]
y <-ifelse(length(x) == 1, x, 
      ifelse(length(x) == 2, mean(x), 
        ifelse(length(x) == 3, 
          ifelse(abs(x[1] - x[2]) == abs(x[2] - x[3]), mean(x), 
            ifelse(abs(x[1] - x[2]) > abs(x[2] - x[3]), mean(x[2:3]),
              ifelse(abs(x[1] - x[2]) < abs(x[2] - x[3]), mean(x[1:2]), 
     "error"))), NA)))
mean_min_diff <- function(x) UseMethod("mean_min_diff")

mean_min_diff.list <- function(x) sapply(x, mean_min_diff.default)

mean_min_diff.default <- function(x) {
  x0 <- sort(x)
  if (length(x0) <= 1) c(x0, NA)[1]
  else if (length(x0) == 2 || sd(diff(x0)) == 0) mean(x0)
  else mean(x0[seq(which.min(diff(x0)), length = 2)])
}
mean_min_diff(x1)
## [1] 6

mean_min_diff(list(x1, x2, x3, x4, x5))
## [1] 6.0 2.5 4.0 1.0 1.0