as.raw and other as.* functions drops the dimension attribute when applied to arrays

Viewed 47

I seem to have a simple problem in R which I've found no simple solution for: I would like to convert an array of integers to raw. Conversion between other simple types have a similar problem. I have found the following non-elegant solutions:

  1. use as.raw and create a new array with the old dimensions:
a <- array(255:261,c(2,3))
b <- array(as.raw(a),dim(a))
  1. use as.raw and reset the dimension attribute:
a <- array(255:261,c(2,3))
b <- as.raw(a)
dim(b) <- dim(a)
  1. change the storage mode
a <- array(255:261,c(2,3))
b <- a
storage.mode(b) <- "raw"

All solutions are really complex for something that should be simple. In solution 1 and 2 as.raw (as other as.* functions) deletes the dim attribute, hence it must be reset. Solution 2 and 3 do not directly support the functional programming style, i.e., they do not return a copy of a with the new type, and, thus, cannot be used easily with piping. I can, of course, make a new function to support functional programming, but my guess is that I'm overlooking something basic. Please enlighten me. Thanks.

2 Answers

Some other ways to convert the type are:

b <- "dim<-"(as.raw(a), dim(a))

b  <- "storage.mode<-"(a, "raw")

b <- apply(a, 2, as.raw)

if the types are compatible, what as.raw is not, you can use:

a[]  <- as.double(a)

Data:

a <- array(55:61,c(2,3))

A not recommended way (thanks to comment from @Roland), as raw is an implicit class, setting it explicitly might have unexpected consequences, is:

b <- a; class(b) <- "raw"

I suggest using your last approach. If the concern is functional programming, well storage.mode<- is a function.

"storage.mode<-"(a, "raw")
#     [,1] [,2] [,3]
#[1,]   ff   00   00
#[2,]   00   00   00
#Warning message:
#out-of-range values treated as 0 in coercion to raw 

a
#     [,1] [,2] [,3]
#[1,]  255  257  259
#[2,]  256  258  260
Related