Does this do what you want?
foo.df <- data.frame(x = rnorm(12), y = runif(12), z = factor(rep(1:3,4)))
bar.mat <- matrix(NA, nrow = ncol(foo.df)-1, ncol = nlevels(foo.df$z))
for(i in 1:(ncol(foo.df)-1))
{
bar.mat[i,] <- xtabs(foo.df[,i] ~ foo.df$z)
}
bar.mat
There's probably a slicker way with apply...
HTH, Andy
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch]On Behalf Of Greg Blevins
> Sent: Monday, November 29, 2004 1:09 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Seeking help with a simple loop construction
>
>
> Hello,
>
> I have a df, pp, with five variables:
>
> > nobs(pp)
> q10_1 q10_2 q10_3 q10_4 actcode
> 1620 1620 1620 1620 1620
>
> I want to create a loop to run four xtabs (the first four
> variables above by the fifth) and then store the results in a
> matrix. Below I make my intent clear by showing the output of
> one xtab which is inserted into a matrix.
>
> > a <- xtabs(q10_1 ~ actcode)
> > a
> actcode
> 1 2 3 4 5 6 7 8 9 10
> 7 11 3 60 66 56 21 40 7 8
>
> > freq.mat <- matrix(0, 4, 10, byrow = TRUE)
> > freq.mat[1,] <- a
> > freq.mat
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
> [1,] 7 11 3 60 66 56 21 40 7 8
> [2,] 0 0 0 0 0 0 0 0 0 0
> [3,] 0 0 0 0 0 0 0 0 0 0
> [4,] 0 0 0 0 0 0 0 0 0 0
> ==============================================================> I have
spent a couple of hours searching the web and my texts but
> continue to strike out in my attempts to construct a correct
> formulation of this simple loop. Help would be appreciated.
>
> Greg Blevins
> The Market Solutions Group, Inc.
> Windows XP
> R 2.0.1
> Pentium 4
> 512 memory
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html