shabbychef / madness

Multivariate Automatic Differentiation R package
GNU Lesser General Public License v3.0
31 stars 0 forks source link

Repto() limitations #18

Closed ZTaylor205 closed 6 years ago

ZTaylor205 commented 6 years ago

Repto works fine if you would like to expand an object, but does not allow you to reshape one. For example, suppose I want to try to reshape a 4x1 vector into a 2x2 array:

> test = c(1,2,3,4)
> test = madness(test)
Warning message:
In madness(test) : no dimension given, turning val into a column
> repto(test,newdim = c(2,2))
Error in blockrep(x, nreps) : all(nreps >= 1) is not TRUE
> repto(test,newdim = c(1,4))
Error in blockrep(x, nreps) : all(nreps >= 1) is not TRUE
> repto(test,newdim = c(4,1))
class: madness 
        d repto(test, c(4, 1))
 calc: ------------------------ 
                d test
  val: 1 ...
 dvdx: 1 0 0 0 ...
 varx:  ...
ZTaylor205 commented 6 years ago

The special case in which you would like to reshape an object without replicating anything can be worked around with:

reshape.madness = function(input,newdims){
  newdat = array(val(input),newdims)
  out = madness(newdat,dvdx(input),xtag = xtag(input))
  return(out)
}

However, this isn't going to cover cases where, e.g., you have a vector of length 8 which you would like to replicate and turn into a 4x4 matrix. You would have to replicate your vector first, then apply the above function.

shabbychef commented 6 years ago

The way this can currently be done in madness is by assigning the dim attribute. So we have:

test = c(1,2,3,4)
test = madness(test)

# repto(test,newdim = c(2,2))
# Error in blockrep(x, nreps) : all(nreps >= 1) is not TRUE
# this works though:
dim(test) <- c(2,2)

# repto(test,newdim = c(1,4))
# Error in blockrep(x, nreps) : all(nreps >= 1) is not TRUE
dim(test) <- c(1,4)

I am personally not crazy about this idiom, since it seems so weird, but it seems to be the way this operation would be done in base R.

ZTaylor205 commented 6 years ago

As mentioned on the other issue, I didn't know about this in base R. Cheers.