Reputation: 24312
Given a data frame like the following, with 2 or more factors:
data <- data.frame(V1=sample(c('A','B','C'), 50, T), V2=sample(c('X','Y'),50,T))
I can produce a barchart of the tabulation of a factor independently, for example:
library(lattice)
with(data, barchart(V1))
How can I produce a multi-panel plot conditioned on the value of the second factor? The syntax I would expect to use is:
with(data, barchart(V1 | V2))
But this produces the following warning:
Warning message:
In Ops.factor(V1, V2) : | not meaningful for factors
and no meaningful output.
Upvotes: 3
Views: 189
Reputation: 115425
When you call with(data, barchart(V1))
you are calling barchart
on an object of class factor and it is calling barchart.default
, which calls the equivalent of barchart(table(V1))
(and thus calls barchart.table
) producing the plot you want.
If you want to have both V1
and V2
included you have to use them in your table, ie.
with(data, barchart(table(V1, V2))
You can then use groups = TRUE
to set the last dimension as the grouping variable
eg
with(data, barchart(table(V1, V2), groups = TRUE))
If you want to use the formula method, you will have to calculate the values yourself beforehand.
eg
library(data.table)
DT <- data.table(data)
barchart(V1~N|V2,DT[, .N,by= list(V1,V2)])
which gives the same result as with(data, barchart(table(V1, V2), groups = TRUE))
Upvotes: 7