I have a large dataframe and want to tabulate all variable-paris. table() and xtabs() both do this, but the problem is:
- xtabs() allows me to drop unused variable levels, which I need, but doesn't let me define the names of the dimensions
- 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?