计算R中具有不同权重和缺失值的加权平均值

时间:2019-03-11 21:49:31

标签: r data.table weighted-average

我正在尝试计算3列的加权平均值,其中权重是根据每行缺失值的计数来确定的。

可复制的示例:

# Some simulated data

N <- 50
df <- data.table(int_1 = runif(N,1000,5000), int_2 = runif(N,1000,5000), int_3 = runif(N,1000,5000))
df[-1] <- lapply(df[-1], function(x) { x[sample(c(1:N), floor(N/10))] <- NA ; x })

# Function to calculate weighted average
# The weights are flexible and are input by user

a = 5
b = 3
c = 2
i = 10

wa_func <- function(x,y,z){

  if(!(is.na(x) & is.na(y) & is.na(z))){

    wt_avg <- (a/i)* x + (b/i) * y + (c/i) * z

  } else if(!is.na(x) & !is.na(y) & is.na(z)){

    wt_avg <- (a/(i-c))* x + (b/(i-c)) * y

  } else if(!is.na(x) & is.na(y) & is.na(z)){

    wt_avg <- a/(i-(b+c))* x

  }

  return(wt_avg)
}

df[, weighted_avg_int := mapply(wa_func,int_1,int_2,int_3)]

但是该函数在一行中输出缺少值的NA。我在这里想念什么?

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要更改函数中第一个if的条件:

wa_func <- function(x, y, z) {
  if (!(is.na(x) | is.na(y) | is.na(z))) {
    wt_avg <- (a / i) * x + (b / i) * y + (c / i) * z

  } else if (!is.na(x) & !is.na(y) & is.na(z)) {
    wt_avg <- (a / (i - c)) * x + (b / (i - c)) * y

  } else if (!is.na(x) & is.na(y) & is.na(z)) {
    wt_avg <- a / (i - (b + c)) * x

  }

  return(wt_avg)
}

您可以通过使用mapply包装函数来改进功能,从而不需要Vectorise()

wa_func <- Vectorize(function(x, y, z) {
  a <- 5 # part of the function?
  b <- 3
  c <- 2
  i <- 10

  if (!(is.na(x) | is.na(y) | is.na(z))) {
    (a / i) * x + (b / i) * y + (c / i) * z
  } else if (!is.na(x) & !is.na(y) & is.na(z)) {
    (a / (i - c)) * x + (b / (i - c)) * y
  } else if (!is.na(x) & is.na(y) & is.na(z)) {
    a / (i - (b + c)) * x
  }
  # no need for return()
})