如果返回值为零,则跳过脚本(我的意思是如果数据帧有空行)

时间:2015-05-29 12:06:03

标签: r ggplot2 rpostgresql

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。所以在这种情况下,如何避免上述错误并只绘制一个图形(我的意思是如果返回值/ dataframe为空则跳过脚本)。

1 个答案:

答案 0 :(得分: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 

然后,您可以执行error handling

tryCatch(myfun(iris[0,]), error = function(e) "alternative result")
#[1] "alternative result"