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

问题描述 投票:0回答:1

我正在尝试计算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用于连续的任何缺失值。我在这里错过了什么?

提前致谢。

r data.table weighted-average
1个回答
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)
}

你可以通过用qazxsw poi包装你的函数来改进函数,所以你不需要qazxsw poi:

mapply
© www.soinside.com 2019 - 2024. All rights reserved.