[R] conditionally weighted mean with NAs

From: Joshua Wiley <jwiley.psych_at_gmail.com>
Date: Sat, 02 Apr 2011 19:20:20 -0700

Dear List,

I am trying to take the weighted average of two numbers (visual acuity measures from the left and right eye). For each row, the lowest value should get a weight of .75, and the highest a weight of .25. My problem is, if one value is missing (NA), the remaining one should get a weight of 1 (i.e., just return the nonmissing value), if both are missing, NA should be returned. Below is some example data and the code I tried to write (Desired is what I actually want). Any thoughts or comments would be welcome.



VA <- cbind(OS = c(.2, 0, 1, -.1, NA, 3, NA),
  OD = c(.3, -.1, .2, -.1, NA, 0, .1),
  Desired = c(0.225, -0.075, 0.4, -0.1, NA, 0.75, 0.1))

## What I tried

weight.combine <- function(left, right) {

  out.r <- right
  out.l <- left
  right <- ifelse(out.r <= out.l, out.r * .75, out.r * .25)
  left <- ifelse(out.r > out.l, out.l * .75, out.l * .25)   rowSums(cbind(left, right), na.rm = TRUE)

## This "works", except it does not handle NAs properly
weight.combine(VA[, "OS"], VA[, "OD"])

Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles

R-help_at_r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Sun 03 Apr 2011 - 02:25:36 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 03 Apr 2011 - 03:10:26 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive