2016-01-31 60 views
0

所有表我試圖產生類似於此的曲線圖:運行MySQL查詢通過R中

enter image description here

從與多個表的數據庫(如x軸)。

數據:

我在數據庫中具有如下幾個表:Table1, Table2, Table3, etc每個表有500+行和列10+(屬性)

的問題

一個這些列中包含該消息的條件(公平,良好,非常好等)。

在數據庫返回此查詢:

SELECT message_condition Condition, 
COUNT(message_id) NumMessage 
FROM `table1` GROUP message_condition 

這將返回:

------------------------ 
Condition | NumMessage 
------------------------ 
      | 80 
Fair  | 20 
Good  | 60 
Ideal  | 50 
Great  | 80 

更新:總是有4個條件有一個空條件(消息沒有條件)。所以,如果我運行所有表的查詢,我將得到與上面相同的表,但具有不同的數字。

現在,我想將這些查詢應用於數據庫中的所有表,所以我可以生成上面的圖(以表格爲x軸)。

我試圖用這個方法:

doCountQuerys <- function(con, table) { 
    query <- paste(' 
     SELECT message_condition Condition, 
     COUNT(message_id) NumMessage FROM`', table, '` GROUP message_condition', sep = '') 
    ts  <- dbGetQuery(con, query) 
    return(ts) 
} 

lists <- dbListTables(con) # get list of all tables in the database 

countz <- numeric(0)  # store the counts for all tables 

for (i in 1:length(list)) { 
    counta <- doCountQuerys(con, lists[i]) 
    countz[i] <- counta[[1]] 
    #print(countz[[1]]) 
} 

,但我得到這個錯誤:

## Warning in countz[i] <- counta[[1]]: number of items to replace is not a 
## multiple of replacement length 

我不認爲我正確地做這個,任何想法如何通過運行該查詢R中的所有表並生成該圖?

+0

您的查詢是否會爲數據庫中的每個表生成相同數量的消息條件和計數? –

+0

@TimBiegeleisen否,每個表的每個條件的消息計數是不同的。例如,對於table1,公平條件的NumMessage爲table2時爲20,公平條件的NumMessage爲80.並且始終有4個條件爲null。 –

回答

3

一些提示。

首先,您需要使用數據框來包含表格名稱,以便在繪圖過程中按此組合。最簡單的方法是使它成爲像

SELECT 'table1' TableName, etc etc 

只是paste它只是添加到您的查詢作爲一個常數考慮在你的函數現有查詢:

query <- paste0("SELECT '", table,"' TableName, COALESCE(NULLIF(message_condition, ''), 'default') message_condition, COUNT(message_id) NumMessage FROM '", table, "' GROUP BY message_condition", sep = '') 

您還應該添加一個默認類別當你的條件爲空時的名字。如圖所示,您可以使用COALESCEISNULL來完成此操作。

編輯 關於它的思考,你只需要rbind每個resutlset你的整體數據框結束在for循環。 R - Concatenate two dataframes?

(順便說一句,應用通常用來代替for循環)

喜歡的東西(未經測試...):

df <- data.frame(TableName=character(), message_condition=character(), NumMessage=integer()) 
for (i in 1:length(lists)) { 
    rbind(df, doCountQuerys(con, lists[i])) 
} 

所以,你應該結束了一個數據幀,看起來像:

TableName, message_condition, NumMessage 
table1, default, 30 
table1, fair, 20 
table1, good, 60 
table1, ideal, 50 
table2, default, 15 
table2, fair, 10 
table2, good, 30 
table2, ideal, 60 
table3, default, 10 
table3, fair, 5 
table3, good, 25 
table3, ideal, 40 

你可以簡單地繪製這樣的:

ggplot(df, aes(x=TableName, y=NumMessage, fill=message_condition)) + geom_bar(stat="identity") 

enter image description here

希望這有幫助,就是你在

之後
+0

是的,問題是,循環不起作用:(如果我添加'SELECT'table1'到查詢,是不是所有表將相同? –

+0

編輯 - 您的循環可以被替換爲單個'rbind'並添加了完整的查詢 –

+0

的事情是,我剛開始學習/使用R,我不知道如何使用rbind –