Skip to content
Prev 325867 / 398503 Next

extracting submatrix from a bigger one

What was suggested gave you a list of data.frames, each named with the ID .
You can use the syntax list$name or list[["name"]] to refer to a data.frame.
  R> splitData <- split(allData, allData$ID)
  R> splitData$x1
    ID value1 value2
  1 x1     10     12
  2 x1     12     22
  3 x1     11      9
  R> splitData$x2
    ID value1 value2
  4 x2     15     10

You seem to want a function that creates a bunch of data.frames in the
current environment instead of one that creates them in a list created to
hold them.  This is not necessary and actually gets in the way most of the
time.

If you want to refer to 'x1' instead of 'splitData$x1' you can use 'with', as in
  R> with(splitData, mean(x1$value2) - mean(x2$value2))
  [1] 4.333333
instead of the slightly wordier
  R> mean(splitData$x1$value2) - mean(splitData$x2$value2)
  [1] 4.333333

If you want to process each sub-data.frame (these are data.frame, not matrices)
you can use lapply() or sapply() or vapply() on the list
  R> dm <- sapply(splitData, function(x)mean(x$value2) - mean(x$value1))
  R> dm
         x1        x2        x3 
   3.333333 -5.000000 -2.500000
  R> dm["x2"]
  x2 
  -5

If you put all those names into the current environment you stand the chance
of clobbering some other dataset whose name matched one of the entries in
allData$ID.  Also you would have to use some rather ugly code involving get()
and assign() to manipulate the objects.  Learn to love lists.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com