[R] holding objects in dataframes

Alexander Shenkin ashenkin at ufl.edu
Fri Jan 14 21:59:53 CET 2011


Hello list,

I need to keep track of objects that are related to particular
observations.  In this case, I need to keep track of polygons that are
associated with observations.  What I would ideally have is one column
of a dataframe hold a "polygonal" object (from the spatstat package). 
My question: I seem to have managed to do it, but as I haven't read that
dataframes are supposed to be able to hold list elements or objects this
way, I wanted to ask if I'm violating things here in a way such that my
code may break in future R releases.  (that is, am i relying on
non-guaranteed behavior).  My other option is to created a named list or
something along those lines, and just match() the dataframe and named
list when i need access to the related objects.  Please see below for
the code.  Thoughts and suggestions are greatly appreciated!

By tinkering around, I've found that dataframe columns do seem to be
able to hold list elements:

a=data.frame(i=c(1,2),j=c(3,4))
z=list(x=c(1,2,3))
a$k=NA
a[1,]$k=z
> str(a)

    'data.frame':   2 obs. of  3 variables:
     $ i: num  1 2
     $ j: num  3 4
     $ k:List of 2
      ..$ : num  1 2 3
      ..$ : logi NA


Extending that behavior, I can attach "polygonal" objects to dataframes
it seems:

library(spatstat)
a=data.frame( a=c(1,2), b=c(3,4) )
a$polygons=NA
a[1,]$polygons = list(disc(radius=50))
> str(a)

    'data.frame':   2 obs. of  3 variables:
     $ a       : num  1 2
     $ b       : num  3 4
     $ polygons:List of 2
      ..$ :List of 5
      .. ..$ type  : chr "polygonal"
      .. ..$ xrange: num  -50 50
      .. ..$ yrange: num  -50 50
      .. ..$ bdry  :List of 1
      .. .. ..$ :List of 4
      .. .. .. ..$ x   : num  50 49.9 49.8 49.5 49 ...
      .. .. .. ..$ y   : num  0 2.45 4.9 7.34 9.75 ...
      .. .. .. ..$ area: num 7851
      .. .. .. ..$ hole: logi FALSE
      .. ..$ units :List of 3
      .. .. ..$ singular  : chr "unit"
      .. .. ..$ plural    : chr "units"
      .. .. ..$ multiplier: num 1
      .. .. ..- attr(*, "class")= chr "units"
      .. ..- attr(*, "class")= chr "owin"
      ..$ : logi NA

> area.owin(a[1,]$polygons[[1]])
[1] 7850.828

thanks,
allie



More information about the R-help mailing list