Reputation: 589
I have a data frame in the following format and I want to get cross tabulation table:
T1 T2
NN NF
FF FF
NF FF
NN NN
NN FF
NF NF
NF NF
FF FF
I can create a simple cross tabulation table by using the table() function
table(T1,T2) Which gives me the following output:
FF FN NF NN
FF 2 0 0 0
FN 0 0 0 0
NF 1 0 2 0
However the factor level NN is dropped by default. Is there a way I can retain the NN level in the table. Which will table output look like:
FF FN NF NN
FF 2 0 0 0
FN 0 0 0 0
NF 1 0 2 0
NN 0 0 0 0
edit:
dput(dataframe) gives:
structure(list(T1 = structure(c(3L, 1L, 2L, 3L, 3L, 2L), .Label = c("FF",
"NF", "NN"), class = "factor"), T2 = structure(c(2L, 1L, 1L,
3L, 1L, 2L), .Label = c("FF", "NF", "NN"), class = "factor")), .Names = c("T1",
"T2"), row.names = c(NA, 6L), class = "data.frame")
Upvotes: 2
Views: 1045
Reputation: 11903
The problem is that "FN" isn't listed in your input data. You can get around this by calling levels()
and informing R that it is one of your levels, it just is a level that does not have any observations in your dataset. For example,
dframe <- read.table(text=" T1 T2
NN NF
FF FF
NF FF
NN NN
NN FF
NF NF
NF NF
FF FF", header=T)
levels(dframe$T1) <- c("FF", "NF", "NN", "FN")
levels(dframe$T2) <- c("FF", "NF", "NN", "FN")
with(dframe, table(T1,T2))
T2
T1 FF NF NN FN
FF 2 0 0 0
NF 1 2 0 0
NN 1 1 1 0
FN 0 0 0 0
One special note: you are overwriting the original levels here, so you need to put the new, nonexistent, level last, otherwise R will call your "NF" level "FN" and lead to all sorts of problems.
Upvotes: 2