poprosiłem to samo pytanie, ale chciałem tylko do korzystania data.table
, ponieważ jest to szybsze rozwiązanie dla znacznie większych zbiorów danych. Zawarłem notatki na temat danych, aby ci, którzy są mniej doświadczeni i chcieli zrozumieć, dlaczego zrobiłem to, co zrobiłem, mogą to łatwo zrobić. Oto w jaki sposób manipulować zbiór mtcars
danych:
library(data.table)
library(scales)
library(ggplot2)
mtcars <- data.table(mtcars)
mtcars$Cylinders <- as.factor(mtcars$cyl) # Creates new column with data from cyl called Cylinders as a factor. This allows ggplot2 to automatically use the name "Cylinders" and recognize that it's a factor
mtcars$Gears <- as.factor(mtcars$gear) # Just like above, but with gears to Gears
setkey(mtcars, Cylinders, Gears) # Set key for 2 different columns
mtcars <- mtcars[CJ(unique(Cylinders), unique(Gears)), .N, allow.cartesian = TRUE] # Uses CJ to create a completed list of all unique combinations of Cylinders and Gears. Then counts how many of each combination there are and reports it in a column called "N"
A oto wezwanie, które produkowane wykres
ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) +
geom_bar(position="dodge", stat="identity") +
ylab("Count") + theme(legend.position="top") +
scale_x_discrete(drop = FALSE)
A produkuje ten wykres:
Ponadto jeśli istnieją dane ciągłe, np. w zestawie danych diamonds
(dzięki mnelowi):
library(data.table)
library(scales)
library(ggplot2)
diamonds <- data.table(diamonds) # I modified the diamonds data set in order to create gaps for illustrative purposes
setkey(diamonds, color, cut)
diamonds[J("E",c("Fair","Good")), carat := 0]
diamonds[J("G",c("Premium","Good","Fair")), carat := 0]
diamonds[J("J",c("Very Good","Fair")), carat := 0]
diamonds <- diamonds[carat != 0]
Wtedy zadziałałoby również użycie CJ
.
data <- data.table(diamonds)[,list(mean_carat = mean(carat)), keyby = c('cut', 'color')] # This step defines our data set as the combinations of cut and color that exist and their means. However, the problem with this is that it doesn't have all combinations possible
data <- data[CJ(unique(cut),unique(color))] # This functions exactly the same way as it did in the discrete example. It creates a complete list of all possible unique combinations of cut and color
ggplot(data, aes(color, mean_carat, fill=cut)) +
geom_bar(stat = "identity", position = "dodge") +
ylab("Mean Carat") + xlab("Color")
dając nam ten wykres:
nie jest tak proste jak ja ufałem, ale nie mógł znaleźć odpowiednią odpowiedź w moim poszukiwaniu tak mam zorientowali zajęłoby trochę przeróbek. Dzięki, Joran. Działa bardzo dobrze +1 –
@TylerRinker Szczerze mówiąc, mam ochotę 'stat_bin (drop = FALSE, geom =" bar ", position =" dodge ", ...)' _długo to zrobi; przynajmniej dokumentacja zdecydowanie sugeruje, że tak. Byłbym bardzo ciekawy, aby usłyszeć od bardziej doświadczonych ludzi na liście mailingowej, dlaczego tak nie jest. – joran
Pracuję teraz nad projektem, ale wyrzucę go na listę później i zgłoś się tutaj. –