[R] Matrixes as data

Ben Bolker bolker at ufl.edu
Fri Oct 16 23:18:19 CEST 2009




Magnus Torfason-2 wrote:
> 
>  > Hola!
>  >
>  > I am working on a problem where data points are (square) matrices. Is
>  > there a way to make a "vector" of matrices, such that it can be stored
>  > in a data.frame?
> 
> I agree with previous posters that in most cases, you would want to 
> store matrices in a list. However, if you already have a bunch of data 
> in a data.frame, and really want your matrices to hang around with that 
> data (for example for persistent storage purposes), you could use the 
> serialize() function to convert them into a string. I have the following 
> functions ("object to character" and "character to object"), that I have 
> used for that exactly:
> 
> 
> # This function stores an R object as a character string.
> # Useful for storing in places that don't accept an R list
> # or other objects.
> otc <- function(o)
> {
>      return(rawToChar(serialize(o, NULL, ascii=TRUE)))
> }
> 
> # This function accepts an object that has been serialized as
> # a character string and returns the original object.
> cto <- function(c)
> {
>      return(unserialize(charToRaw(c)))
> }
> 
> # Demo code
> x <- matrix(1:4,nrow=2)
> s <- otc(x)
> d <- data.frame(a=c,stringsAsFactors=FALSE)
> cto(d$a[1])
> 
> 

The alternative, if you're going to be working with these kinds of data *a
lot*,
is to create a class for the matrices+auxiliary data object (for S3, you can
store this as a list of (list of matrices, data frames); for S4, store the
list
of matrices and the data frame as separate slots in the object). Then write
accessor functions that make sense.

-- 
View this message in context: http://www.nabble.com/Matrixes-as-data-tp25927469p25932504.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list