मैं इस एक ही सवाल पूछा, लेकिन मैं केवल, data.table
उपयोग करने के लिए के रूप में यह बहुत बड़ा डेटा सेट के लिए एक तेजी से समाधान है चाहता था। मैंने डेटा पर नोट्स शामिल किए ताकि वे कम अनुभवी हों और समझ सकें कि मैंने जो किया है, मैंने ऐसा क्यों किया है। यहाँ कैसे मैं mtcars
डेटा सेट चालाकी से है:
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"
और यहाँ कॉल कि ग्राफ
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)
उत्पादित है और यह इस ग्राफ का उत्पादन: इसके अलावा
, यदि निरंतर डेटा है, तो diamonds
डेटा सेट (एमनेल के लिए धन्यवाद) में:
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]
फिर 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")
हमें इस ग्राफ देते:
नहीं के रूप में आसान के रूप में मुझे उम्मीद थी, लेकिन मेरी खोज तो मैं यह कुछ नए सिरे ले जाएगा सोचा जाना चाहिए था में एक उपयुक्त जवाब नहीं मिल सका। धन्यवाद जोरेन। बहुत अच्छी तरह से काम किया +1 –
@ टायलर रिंकर ईमानदारी से, मुझे लगता है कि 'stat_bin (ड्रॉप = गलत, geom = "bar", स्थिति = "डॉज", ...) '_should_ ऐसा करें; कम से कम, दस्तावेज़ीकरण दृढ़ता से सुझाव देता है कि यह होगा। मेलिंग सूची पर अधिक जानकार लोगों से सुनने के लिए मैं बहुत उत्सुक हूं कि ऐसा क्यों नहीं होता है। – joran
मैं अभी एक परियोजना पर काम कर रहा हूं लेकिन मैं इसे बाद में सूची में फेंक दूंगा और यहां वापस रिपोर्ट करूंगा। –