[R] Average 2 Columns when possible, or return available value

From: emorway <emorway_at_engr.colostate.edu>
Date: Fri, 25 Jun 2010 16:08:12 -0700 (PDT)

Forum,

Using the following data:

DF<-read.table(textConnection("A B
22.60 NA
 NA NA
 NA NA
 NA NA
 NA NA
 NA NA
 NA NA
 NA NA

102.00 NA
 19.20 NA
 19.20 NA

 NA NA
 NA NA
 NA NA
 11.80 NA
 7.62 NA
 NA NA
 NA NA
 NA NA
 NA NA
 NA NA
 75.00 NA
 NA NA
 18.30 18.2
 NA NA
 NA NA
 8.44 NA
 18.00 NA
 NA NA
 12.90 NA"),header=T)
closeAllConnections()

The second column is a duplicate reading of the first column, and when two values are available, I would like to average column 1 and 2 (example code below). But if there is only one reading, I would like to retain it, but I haven't found a good way to exclude NA's using the following code:

t(as.matrix(aggregate(t(as.matrix(DF)),list(rep(1:1,each=2)),mean)[,-1]))

Currently, row 24 is the only row with a returned value. I'd like the result to return column "A" if it is the only available value, and average where possible. Of course, if both columns are NA, NA is the only possible result.

The result I'm after would look like this (row 24 is an avg):

 22.60

    NA
    NA
    NA
    NA
    NA
    NA
    NA

102.00
 19.20
 19.20

    NA
    NA
    NA
 11.80
  7.62
    NA
    NA
    NA
    NA
    NA
 75.00

    NA
 18.25

    NA
    NA
  8.44
 18.00

    NA
 12.90

This is a small example from a much larger data frame, so if you're wondering what the deal is with list(), that will come into play for the larger problem I'm trying to solve.

Respectfully,
Eric

-- 
View this message in context: http://r.789695.n4.nabble.com/Average-2-Columns-when-possible-or-return-available-value-tp2269049p2269049.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 25 Jun 2010 - 23:11:06 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 Sat 26 Jun 2010 - 00:40:35 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