Frequency form to case form - unexpected values in table I'm taking count data on voting preferences by race and entering it into a table in frequency form, then expanding out to case form and using CrossTable to look at adjusted residuals. Here's my script:

### create table in frequency form 
vnames &lt;- c("Race", "Party", "freq")
a &lt;- c("White","Dem", 871)
b &lt;- c("White","Ind", 444)
c &lt;- c("White","Rep", 873)
d &lt;- c("Black","Dem", 302)
e &lt;- c("Black","Ind", 80)
f &lt;- c("Black","Rep", 43)

rtable &lt;- rbind(a,b,c,d,e,f)
colnames(rtable) &lt;- vnames

###check table - looks fine
head(rtable)

###expand to case form
rtablecase &lt;- expand.dft(rtable, freq = "freq")

###check table - *here's where it gets weird*.
head(rtablecase)


The first two rows hold the value of "1" in the race column rather than "White". Everything else is as expected. Why? I eventually just manually replaced the values (see below) so I could run CrossTable and it looks fine, but can someone please tell me where these two 1s are coming from?*

### replace 1s in Race column 
rtablecase[1,1] &lt;- "White"
rtablecase[2,1] &lt;- "White"

###convert to data frame
rtcasedf &lt;- data.frame(rtablecase)
head(rtcasedf)

###Crosstabulation with adjusted residuals
CrossTable(rtcasedf$Race, rtcasedf$Party, format="SPSS", asresid=TRUE, chisq=TRUE)
The behavior seems to be due to a bug in the expand.dft function. I created a simple function myfun that allows you to create a matrix similar to the one created by expand.dft. 

myfun &lt;- function(x, freq = "Freq") {
  # repeat the row indices according to `freq`
  idx &lt;- rep(seq(nrow(x)), as.integer(x[, freq]))
  # expand matrix and ignore `freq` column
  x[idx, colnames(x) != freq]
}


Note that is function is not meant to replace expand.dft but works for simple cases only.

Try it with your data set rtable:

rtablecase &lt;- myfun(rtable, freq = "freq")


The result:

head(rtablecase)
#   Race    Party
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"