2016-01-31 56 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 –