[R] data frame to array

Bill.Venables at csiro.au Bill.Venables at csiro.au
Mon Mar 23 00:39:35 CET 2009

Here is a possibility

Dat <- cbind(expand.grid(f1 = letters[1:5], f2 = LETTERS[1:5], 
			f3 = as.character(1:5)), x = rnorm(125))
M <- with(Dat, {
	  f23 <- f2:f3
	  m <- matrix(0, length(levels(f1)), length(levels(f23)))
	  i <- match(f1, levels(f1))
	  j <- match(f23, levels(f23))
	  m[cbind(i,j)] <- x
	  dimnames(m) <- list(levels(f1), levels(f23))

> M[1:5, 1:5]
          A:1        A:2        A:3        A:4        A:5
a  1.72686085 -2.0605242  1.0989119  0.8096139  1.0146972
b -0.34512446 -0.1709805  0.3401842  0.5815685 -1.4862872
c  1.14489491 -0.3959085  0.3222197 -1.1108793  0.3676764
d  0.02520386 -1.0018102 -0.7232067 -0.6142914  0.6694813
e -1.23366653  0.3826862 -0.6797035  0.6536055  0.8865669

This should work provided you have one entry per f1 x f2 x f3 cell.  The rows of the data frame may be in arbitrary order.  

Bill Venables

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Thomas S. Dye
Sent: Monday, 23 March 2009 7:36 AM
To: r-help at r-project.org
Subject: [R] data frame to array

Aloha all,

I have a data frame with 4 columns.  The first three are factors (f1,  
f2, f3) and the fourth is numeric.  I'd like to explore these data  
using median polish.  To do that I plan to use medpolish() on the  
matrix[f1,f2xf3], then medpolish on the resulting matrix[f2,f3].  This  
approach is described by Cook on page 141 of Exploring Data Tables,  
Trends, and Shapes.

split() gets me close to where I want to be, but results in a list,  
rather than a matrix.  How do I construct the matrix[f1,f2xf3] from my  
data frame?

Also, any pointers to existing code that performs multi-way median  
polish will be appreciated.

Sorry for the newbie-type query, but manipulating data prior to  
analysis is really hard for me in R.

All the best,

Thomas S. Dye, Ph.D.
T. S. Dye & Colleagues, Archaeologists, Inc.
Phone: (808) 529-0866 Fax: (808) 529-0884

	[[alternative HTML version deleted]]

R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list