【发布时间】:2023-03-31 20:00:01
【问题描述】:
我正在尝试生成类似于此的图表:
来自具有许多表的数据库(作为 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 中的所有表中运行该查询并生成该图吗?
【问题讨论】:
-
您的查询是否会为数据库中的每个表生成相同数量的消息条件及其计数?
-
@TimBiegeleisen 不,每个表的每个条件的消息计数都不同。例如table1,公平条件的NumMessage为20,而table2,公平条件的NumMessage为80。并且总是有4个条件为空。