0

I'm trying to calculate the weighted average of 3 columns where the weights are decided based on the count of missing values per row.

A reproducible example:

# 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)]

But the function outputs NA for any missing value in a row. What am I missing here?

Thanks in advance.

Debbie
  • 391
  • 2
  • 18

1 Answers1

1

You need to change condition of the first if in your function:

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)
}

You can improve the function so you don need mapply by wrapping your function with 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()
})
Bulat
  • 6,869
  • 1
  • 29
  • 52
  • Both the solutions work perfectly. `return` is not required for any of the functions. `a`,`b`,`c`,`i` are user inputs and I have defined them outside the function. – Debbie Mar 11 '19 at 23:28
  • 1
    its better not to use vars from externals scope inside the function. you can always pass them as arguments – Bulat Mar 12 '19 at 08:14