[R] spinning and flipping arrays
Bill Rising
brising at louisville.edu
Tue May 27 03:44:27 CEST 2003
On 5/26/2003 17:21, Peter Dalgaard BSA wrote
>Bill Rising <brising at louisville.edu> writes:
>
>> On 5/26/2003 15:05, Spencer Graves wrote
>>
[snip...]
This seems to work for the flipping (and it relies on textual
representations, and is completely unreadable, and is inelegant):
fliparr <-
function(arr,dims=length(dim(arr))) {
#defaults to flipping across last dimension, otherwise takes
# a vector of dimensions (which ignores dimesions which are out of
bounds)
# NO error checking yet
# initialize a series of blank strings for the indices
strarg <- vector("character",arrsize <- length(arrdim<-dim(arr)))
# find which indices will be flipped (logical vector)
which <- apply(outer(1:arrsize,as.vector(dims),"=="),1,any)
# use 1:dimension size for non-flipped dimensions
strarg[!which] <- paste(NULL,arrdim[!which],sep="1:")
# use dimension size:1 for flipped dimensions
strarg[which] <- paste(arrdim[which],NULL,sep=":1")
# paste all the text together and hope syntax never changes
eval(parse(text=paste("arr[",paste(strarg,collapse=","),"]",collapse="")))
}
>
>Relying on textual representation always looks dodgy to me.
You've got a good point.
>How about
>
>spin <- function(x,amount=c(1,rep(0,length(dim(x))-1))) {
> indices <- mapply(function(n,k) (seq(length=n)+k-1)%%n + 1,
> dim(x),amount, SIMPLIFY=FALSE)
> do.call("[", c(list(x), indices))
>}
This works quite well for spinning an equal amount in each dimension. I
think I can use this to work on the equivalent to APL which either uses a
single number to spin a single dimension (like spin(foo,c(something,0,0))
) or an array with the dimensions of the original array minus the
dimension around which items are spun, so that the items can be shifted
differenent amounts.
>
>(Note: mapply() was introduced in 1.7.0).
I'll check out mapply. thanks,
Bill
More information about the R-help
mailing list