[R] Including a ggplot call with a conditional geom in a function

phii m@iii@g oii phiiipsmith@c@ phii m@iii@g oii phiiipsmith@c@
Thu Mar 25 03:24:21 CET 2021

How can I write an R function that contains a call to ggplot within it, 
with one of the ggplot geom statements being conditional? In my reprex, 
I want the plot to contain a horizontal zero line if the y values are 
both positive and negative, and to exclude the horizontal line if all of 
the y values are of the same sign. I tried a simple if statement, but it 
does not work. Suggestions appreciated. Philip


a <- c(1:8)
b <- c(23,34,45,43,32,45,68,78)
c <- c(0.34,0.56,0.97,0.33,-0.23,-0.36,-0.11,0.17)
df <- data.frame(a,b,c)

posNeg <- function(x) {
   ifelse(sum(x>0)>0 & sum(x>0)<length(x), y <- TRUE,y <- FALSE)
plotLineFunc <- function(MYdf,MYx,MYy) {
     #if(posNeg({{MYy}})) geom_hline(yintercept=0,size=0.2)+   # This 
does not work
(plot1 <- plotLineFunc(df,a,b))
(plot2 <- plotLineFunc(df,a,c))

More information about the R-help mailing list