library(RPostgreSQL)
library(ggplot2)
I want to collect some data from database using Rpostgresql and want to make bar graph for it. Here is the script
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)
Normally I run the complete script using source('filename') command. And when return value of l1 and l2 has rows(I mean dataframe), I will get the required output.
But,in some cases if the return value of l1 is equal to zero(no of rwos is zero) or l2 is equal to zero(no of rows is zero), then i will get an error:
Error in cut.default(l2$eventtime, breaks = "hour") :
'x' must be numeric
I know these error is because of empty dataframe l2. so in these kind of situation, how to avoid the above error and plot only one graph(I mean to skip the script if the return value/dataframe is empty).