[R] Matrixes as data

Magnus Torfason zulutime.net at gmail.com
Fri Oct 16 20:22:51 CEST 2009


 > 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])




More information about the R-help mailing list