[R] how to emerge two tables by taking the ave.

jim holtman jholtman at gmail.com
Sun Nov 11 23:27:50 CET 2007


Here is one way of doing it:

> x
     [,1] [,2] [,3]
[1,]    2    4    6
[2,]    1    2   NA
[3,]    4    6   NA
> y
     [,1] [,2] [,3]
[1,]   NA    4    4
[2,]    2    2   NA
[3,]    1    2    2
> z <- mapply(function(a,b)mean(c(a,b), na.rm=TRUE), x, y)
> dim(z) <- dim(x)
> z
     [,1] [,2] [,3]
[1,]  2.0    4    5
[2,]  1.5    2  NaN
[3,]  2.5    4    2
> # to change it to NA
> is.na(z) <- is.nan(z)
> z
     [,1] [,2] [,3]
[1,]  2.0    4    5
[2,]  1.5    2   NA
[3,]  2.5    4    2
>
>


On Nov 11, 2007 4:52 PM, affy snp <affysnp at gmail.com> wrote:
> Dear list,
>
> I am new to R and very inexperienced. Sorry for the trouble.
> I have two txt files and want to merge them by taking the average.
> More specifically, for example, the txt file1, with row names and column names,
> consists of 238000 rows and 196 columns. Each column corresponds
> to a sample. The data is mixed with numeric or NA. So what I plan to
> do is:
>
> (1) Take the 1st column from txt file 1 and txt file 2, calculate the average
> if both numbers are numeric. If one is numeric and the other one is NA or
> the opposite, just use the numeric; If both are NA, then use NA, Do all this
> for all columns
> (2) Create txt file 3 with the numbers from the above and add the row names and
> column names.
>
> So an illustrative example could be:
>
> txt file 1
>
>             A       B       C
> row1      2       4        6
> row2      1       2       NA
> row3      4       6       NA
>
> txt file 2
>
>            A        B      C
> row1     NA      4       4
> row2     2         2      NA
> row3     1         2      2
>
> then txt file 3 will be created as:
>
>            A        B       C
> row1     2         4       5
> row2    1.5       2       NA
> row3    2.5       4       2
>
> Any help will be appreciated.
>
> Thanks!
>       Allen
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list