Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge multi-dimensional arrays

Tags:

arrays

r

I have a list of arrays in which each array has only 2 elements with numbers and otherwise NA. There is only 1 number for any given element in all the arrays combined.

here is some example data.

ar1=array(NA,dim=c(2,3,4))
ar1[1,1,1]=100
ar2=array(NA,dim=c(2,3,4))
ar2[2,3,4]=200
ar3=array(NA,dim=c(2,3,4))
ar3[2,1,4]=300
ar=list(ar1,ar2,ar3)

Thanks!

like image 725
Dominik Avatar asked Dec 01 '25 03:12

Dominik


2 Answers

pmax has an na.rm argument and you can pass ar as a list along with that argument to pmax with do.call:

> do.call(pmax, c(ar,  na.rm=TRUE) )
, , 1

     [,1] [,2] [,3]
[1,]  100   NA   NA
[2,]   NA   NA   NA

, , 2

     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]   NA   NA   NA

, , 3

     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]   NA   NA   NA

, , 4

     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]  300   NA  200
like image 83
IRTFM Avatar answered Dec 05 '25 16:12

IRTFM


You could use Reduce with any vectorized function that ignores NAs:

Reduce(function(x, y) ifelse(!is.na(x), x, y), ar)

Another example:

library(functional)
Reduce(Curry(pmax, na.rm = TRUE), ar)
like image 23
flodel Avatar answered Dec 05 '25 14:12

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!