Skip to content

Seeking help with a simple loop construction

2 messages · Greg Blevins, Andy Bunn

#
Hello,

I have a df, pp, with five variables:
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.
actcode
 1  2  3  4  5  6  7  8  9 10 
 7 11  3 60 66 56 21 40  7  8
[,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
#
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
http://www.R-project.org/posting-guide.html