i hoping able construct do.call formula subsetting without having identify actual range of every dimension in input array. problem i'm running can't figure out how mimic direct function x[,,1:n,] , no entry in other dimensions means "grab elements."
here's sample code, fails. far can tell, either [ or do.call replaces null list values 1 index.
x<-array(1:6,c(2,3)) dimlist<-vector('list', length(dim(x))) shortdim<-2 dimlist[[shortdim]] <- 1: (dim(x)[shortdim] -1) flipped <- do.call(`[`,c(list(x),dimlist)) i suppose kludge solution assigning value -2*max(dim(x)) each element of dimlist, yuck.
(fwiw, have alternate functions desired job either via melt/recast or dreaded "build string , eval(parse(mystring)) , wanted "better.")
edit: aside, ran version of code (with equivalent of dwin's true setup) against function used melt & acast ; latter several times slower no real surprise.
after poking around, alist seems trick:
x <- matrix(1:6, nrow=3) x [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 # 1st row do.call(`[`, alist(x, 1, )) [1] 1 4 # 2nd column do.call(`[`, alist(x, , 2)) [1] 4 5 6 from ?alist:
‘alist’ handles arguments if described function arguments. values not evaluated, , tagged arguments no value allowed whereas ‘list’ ignores them. ‘alist’ used in conjunction ‘formals’.
way of dynamically selecting dimension extracted. create initial
alist of desired length, see here (hadley, using bquote) or here (using alist). m <- array(1:24, c(2,3,4)) ndims <- 3 <- rep(alist(,)[1], ndims) for(i in seq_len(ndims)) { slice <- slice[[i]] <- 1 print(do.call(`[`, c(list(m), slice))) } [,1] [,2] [,3] [,4] [1,] 1 7 13 19 [2,] 3 9 15 21 [3,] 5 11 17 23 [,1] [,2] [,3] [,4] [1,] 1 7 13 19 [2,] 2 8 14 20 [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
Comments
Post a Comment