2

I have a large dataframe and want to tabulate all variable-paris. table() and xtabs() both do this, but the problem is:

  1. xtabs() allows me to drop unused variable levels, which I need, but doesn't let me define the names of the dimensions
  2. table() allows me to define dimension names, but not to drop the unused levels.

The reason I need to define the dimensionnames is that all this happens inside a for-loop (becasue I need to do 'everybody by everybody'), and this renders the names meaningless. Below is a 'simple' example to show what I mean.

var.3=factor(rep(c("m","f","t"), c(5,5,2)))
df <- data.frame(var.1=rep(1:4, 1:4), var.2=rep(c("A","B"), 5), var3=var.3[1:10])
levels(df[,3])           # the "t" level is not in the df!
tabs.list<- list()
xtabs.list<- list()
for (i in 1:(ncol(df)-1)){
  for (j in (i+1):ncol(df)) {
    tabs.list[[paste(sep=" ", colnames(df)[i], "by",colnames(df)[j])]] <-
      table(df[,i],df[,j], dnn=list(colnames(df)[i], colnames(df)[j]))
    xtabs.list[[paste(sep=" ", colnames(df)[i], "by",colnames(df)[j])]] <-
      xtabs(~df[,i]+df[,j], drop.unused.levels=TRUE)
  }
}
tabs.list
xtabs.list
#What I want: 
for (i in 1:length(xtabs.list)){
names(dimnames(xtabs.list[[i]])) <- names(dimnames(tabs.list[[i]]))
}
xtabs.list

So two functions for crossclassifying data each have an option I would like to use!? Why can't I do both?

maja zaloznik
  • 660
  • 9
  • 24

1 Answers1

2

It's pretty easy to "de-factorize" arguments by wrapping in as.character

tabs.list<- list()
for (i in 1:(ncol(df)-1)){
    for (j in (i+1):ncol(df)) {
      tabs.list[[paste(sep=" ", colnames(df)[i], "by",colnames(df)[j])]] <-
        table( as.character(df[,i]), 
               as.character(df[,j]), 
               dnn=list(colnames(df)[i], colnames(df)[j])) 
                              }
                           }
tabs.list
IRTFM
  • 258,963
  • 21
  • 364
  • 487