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!
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With