0
library(RPostgreSQL)
library(ggplot2)  

我想使用 Rpostgresql 从数据库中收集一些数据,并想为它制作条形图。这是脚本

l1 <- dbGetQuery(con, "SELECT * FROM event_log where eventtime > '2015-05-29 06:00:00' and sourceid = '1' order by eventtime ")

my_count_table1 <- table(cut(l1$eventtime, breaks = "hour"))
l1_count <- data.frame(my_count_table1)
l1_count$Var1 <- as.POSIXct(l1_count$Var1, format="%Y-%m-%d %H:%M:%S")
p1 <- ggplot(l1_count, aes(x = Var1, y = Freq)) + geom_bar()

l2 <- dbGetQuery(con, "SELECT * FROM event_log where eventtime > '2015-05-29 06:00:00' and id = '3' order by eventtime ")

my_count_table2 <- table(cut(l2$eventtime, breaks = "hour"))
l2_count <- data.frame(my_count_table2)
l2_count$Var2 <- as.POSIXct(l2_count$Var1, format="%Y-%m-%d %H:%M:%S")
p2 <- ggplot(l2_count, aes(x = Var1, y = Freq)) + geom_bar()

multiplot(p1, p2, cols=2)

通常我使用 source('filename') 命令运行完整的脚本。当 l1 和 l2 的返回值有行(我的意思是数据帧)时,我将得到所需的输出。

但是,在某些情况下,如果 l1 的返回值等于零(rwos 的数量为零)或 l2 等于零(行的数量为零),那么我会得到一个错误:

Error in cut.default(l2$eventtime, breaks = "hour") : 
  'x' must be numeric

我知道这些错误是因为空数据框 l2。所以在这种情况下,如何避免上述错误并只绘制一个图(我的意思是如果返回值/数据框为空则跳过脚本)。

4

1 回答 1

0

将您的代码包装在一个函数中并进行适当的输入检查。这是一个简化的示例:

myfun <- function(DF) {
  stopifnot(nrow(DF) > 0)
  return("result of calculations")

}

myfun(iris)
#[1] "result of calculations"
myfun(iris[0,])
#Error: nrow(DF) > 0 is not TRUE 

然后您可以进行错误处理

tryCatch(myfun(iris[0,]), error = function(e) "alternative result")
#[1] "alternative result"
于 2015-05-29T12:21:03.573 回答