[R] Apply approx() to an array and eventually a list of arrays

Folkes, Michael Michael.Folkes at dfo-mpo.gc.ca
Thu Oct 20 22:43:47 CEST 2011


Hello all,
I'm struggling to grasp how I might use lapply() instead of looping to
run approx() on a list consisting of multiple arrays - each of equal
dimension.
But simpler than that, I haven't been able to successfully apply
approx() to an array, unless I loop through the third dimension and
extract the matrix. See example code below...
Any suggestions will be gratefully received.
Thanks
Michael



################### CODE START


# build array, create data gaps (i.e. NA's), attempt to apply approx()
arr.dim<-c(20,3,2)
test.arr<-array(rnorm(prod(arr.dim)),dim=arr.dim)
test.arr.filled<-array(NA,dim=arr.dim)
test.arr[9:13,1,1]<-NA #create some data gaps

### I can only get approx() to work if I loop through third dimension of
the array
for(i in 1:dim(test.arr)[3]){
  test.mat<-test.arr[,,i]
 
linear.interp.list<-apply(test.mat,MARGIN=2,FUN=approx,xout=1:nrow(test.
mat),x=1:nrow(test.mat))
  test.arr.filled[,,i]<-matrix(
sapply(linear.interp.list,'[[','y'),ncol=ncol(test.mat),byrow=FALSE)
  }
#### How to use approx() on array?
# this clearly doesn't work
apply(test.arr,MARGIN=2,FUN=approx,xout=1:nrow(test.arr),x=1:nrow(test.a
rr))

  
#################### Now apply approx() to a list of arrays?
# build list of 2 arrays of equal dim, create NA's, attempt to apply
approx()
arr.dim<-c(20,3,2)
test.list<-list(a=array(rnorm(prod(arr.dim)),dim=arr.dim),b=array(rnorm(
prod(arr.dim)),dim=arr.dim))
test.list[['a']][9:13,1,1]<-NA
xout<-1:nrow(test.list[['a']])
lapply(test.list, FUN=approx,xout=xout) # clearly doesn't work
######################### CODE END

_______________________________________________________
Michael Folkes
Salmon Stock Assessment
Canadian Dept. of Fisheries & Oceans     
Pacific Biological Station
3190 Hammond Bay Rd.
Nanaimo, B.C., Canada
V9T-6N7
Ph (250) 756-7264 Fax (250) 756-7053  Michael.Folkes at dfo-mpo.gc.ca



More information about the R-help mailing list