Non-numeric argument to binary operator in Shiny using ggplot - r

I am writing my first Shiny app trying to port a code for plotting maps of Spain into a Shiny app that anyone with no knowledge of R can use.
Lately I have come up with a problem when trying to alter a ggplot returned by a function.
I will post a simplified version of my code.
I first have a function in helper.R that takes various inputs from the ui and returns a gg and a dataframe:
graphing=function(datax,setter,selCCAA,varsel){
map=readShapeSpatial('prov_map.shp')
map#data$CodProv=as.integer(map#data$CodProv)
map#data=merge(map#data,datax,by.x='CodProv',by.y='CodProv',sort=F)
map#data$id=rownames(map#data)
map.points=fortify(map,region='id')
map.df=join(map.points,map#data,by='id')
map.df$Cd_CCAAint=as.integer(map.df$Cd_CCAA)
if(varsel=="-"){return (NULL)}
else {
if (setter==0){
mapa=ggplot(map.df)+
aes_string("long","lat",group="group",fill=varsel)+
geom_polygon()+
geom_path(color='white')+
coord_equal()
return(list(mapa,map.df))
}
else {
map.dfx<-subset(map.df,map.df$Cd_CCAAint==selCCAA)
mapa=ggplot(map.dfx)+
aes_string("long","lat",group="group",fill=varsel)+
geom_polygon()+
geom_path(color='white')+
coord_equal()
return(list(mapa,map.dfx))
}
}
}
Then, in server.R, I take the gg that is returned by the function and add more lines to it so the user can personalize the graphs' colors, midpoint etc.
output$plot=renderPlot({
mapa=graphing(dataini,input$setter,input$selCCAA,input$varsel)
grafico=mapa[[1]]+
scale_fill_gradient2(low='#89D1F3',high='#006EC1')+
theme(legend.position='bottom',axis.title.x=element_blank(),
axis.title.y=element_blank(),axis.ticks=element_blank(),axis.text=element_blank(),
panel.grid.minor=element_blank(),panel.grid.major=element_blank())
grafico
})
When I run the app including the line scale_fill_gradient2 or any type of geom I get the following error:
Warning: Error in +: non-numeric argument to binary operator
The error does not appear when I just include the theme.
Up to now, the two lines had been included in the graphing function and the App had been running perfectly*, but I need them to be in server.R so the graph can be personalized as stated before.
*:that version of the App can be tested using runGitHub("Mapas_BBVA_provincias","IArchondo"). Any help with the display of spanish characters such as ñ in the ui, would be extremely welcome as well.

That's the error you get from
NULL + scale_fill_gradient2(low='#89D1F3',high='#006EC1')
Since your graphing function begins with if(varsel=="-"){return (NULL)}, my guess is this error is created when varsel is "-". Try returning a blank ggplot object instead when nothing is selected.
if(varsel=="-"){return (ggplot())}

Related

Unexplained R failure: Error: attempt to use zero-length variable name

I am trying to specify the size of a plot dynamically in RMarkdown. Because it is a facetted plot with a dynamic number of plots, the aspect ratio needs to change.
I'm using this code:
...
jobs_levels <- 9
```
#### Figure 3.1.1. Effect of Inidivdual Interventions in Living Rooms
```{r figure_3_3_1, fig.height=jobs_levels}
jobs_levels
print(figure_3_3_1)
```
For the sake of simplicity, I've hard coded the jobs_levels (the number of levels in the facetting factor). As you can see, I set the value very clearly,and then use it in the very next code chuck. I can see the value clear as day in the environment. It is 9. But I get this:
Error in eval(ele) : object 'jobs_levels' not found
> ```{r figure_3_3_1, fig.height=jobs_levels}
Error: attempt to use zero-length variable name
When I run this in batch mode, it crashes. Any idea what is going on with this?
I even put in the extra lines:
jobs_levels
to debug. EAch time I run one of those lines with cotrl enter, it evaluates right, but I see the error message again too...
The error message makes it look as though you are trying to evaluate the chunk header as R code. You had
```{r figure_3_3_1, fig.height=jobs_levels}
The first two backticks would be parsed as a zero length variable name, as the error message states.
You can't run R Markdown code as R code, you need to use rmarkdown::render or a related function to run it.

ggplot2 error: Error in default + theme : non-numeric argument to binary operator

I have been getting the error Error in default + theme : non-numeric argument to binary operator. I have been using R and teaching R for a long time but I can't find this problem. I have included a reproducible example that fails this way below:
library(tibble)
library(ggplot2)
brains <- as_tibble(brains)
brains <- brains[1:10, ]
brains
ggplot(brains, aes(x = BodyWt, y = BrainWt)) +
geom_point()
The error occurs when executing the ggplot() statement.
My hardware is an HP Laptop 15-ef0xxx. I am running Windows 10 Home version 2004. I am running RStudio community edition "Water Lily" and R version R x64** 4.0.2.
I know this is a simple error and it is driving me crazy.
So I finally solved this problem. On the github issue I had opened Hiroaki commented that "One possibility is that you might set a invalid default theme in your .Rprofile, but I'm not sure..." (see link to issue below).
I'm not sure if your R file is part of a project but mine is.
So I went back and deleted the theme_set() line in my R file, went in and double checked all my project options and selected the option "Disable .Rprofile execution on session start/resume" and "Quit child processes on exit". And then I restarted the R session and now everything works. Including on the default R editor console.
I'm not sure if all those steps are necessary but that seemed to do the trick for me! Hope it helps.
I thought this was an RStudio issue but it seems it's possibly a ggplot2 > problem. I have verified using two different datasets that the same >error comes up when I try using ggplot2 in RStudio or using the default R >console. I get the exact same error with code that's been working fine >but now suddenly won't. I have opened an issue on Github (ggplot2) with a >reprex. Might be worth checking there: >https://github.com/tidyverse/ggplot2/issues/4177
I know this is not an answer per se but I don't have enough reputation >points to add a comment to the previous answer but I thought linking to >the issue on Github might help.
I think you have numbers quoted somewhere and you are trying to perform mathematical operation on character values. Consider
x <- c("5","6")
y <- x/1
> y <- x/1
Error in x/1 : non-numeric argument to binary operator
Now try converting x to numeric and perform the same operation.
y <- as.numeric(x)/1
> y
[1] 5 6
So, you need to use as.numeric on your variable.
The following should resove this issue
ggplot(brains, aes(x = as.numeric(BodyWt), y = as.numeric(BrainWt)))

grDevices::dev.new() does not work in the first time

My question: How to let grDevices::dev.new() work well ?
To avoid the error Error in plot.new() : figure margins too large coursing the small plot region,
I wrote the code grDevices::dev.new() in the front of plot().
However this code does not work in the first time (or after pushing the button .clean all plot button )
And this cause the errors (e.g., in the R CMD check).
Do I misunderstand the function grDevices::dev.new() ?
REF?:
R: Open new graphic device with dev.new() does not work
Answer
Using grDevices::windows() instead of grDevices::dev.new(), I overcome the issues.
Unfortunately, we cannot use grDevices::windows() , because the following error occurs in the R CMD check:
Error in grDevices::windows() :
screen devices should not be used in examples etc

R shiny: validate(need()) with dateRangeInput

I've read the help pages and shiny webpages on validate() and need() 10 times, googled all variations I could think of, but I simply cannot find what is wrong with my code.
The only thing I require is for my app to show a custom error instead of the (empty) plot when a user inputs a wrong date range = 2nd date earlier than the 1st.
output$plotTemp <- renderPlot({
req(input$button)
validate(need(input$datums[1] < input$datums[2], "error: end date earlier than start"))
isolate({buttonFeedbackServer("button", { # if validate = ok, run functions
importdata(input$jaartal)
weerstation <- which(weerstations == input$weerstation)
temperatuur(input$datums, weerstation) # create plot
})
})
})
I get this error now: no applicable method for 'validate' applied to an object of class "NULL"
I bet it's gonna be something stupid, but I spent hours and hours on this without seeing it...
Without validate() everything works perfect, so it's no mistake in other code.
My R, Rstudio and all packages have been updated last week.
Other packages, including jsonlite have a validate function. This error can occur when you accidentally are using a validate function from a different package. Try using shiny::validate instead to make sure you are using the correct validate.

rCharts and highcharts with shiny plot does not update correctly

I've created a custom plotting function for a scatterplot with error bars on multiple series using rCharts. I successfully embedded said plot in a shiny application. The first time it shows everything works fine:
However, if I try to update the plot (e.g. by changing some input) the plot does not change and I get the following JS error message on the browser's console:
TypeError: 'undefined' is not a function (evaluating 'this[b].destroy()')
The strange thing is that if I check the plot object (p) it seems fine, e.g. I can plot it in Rstudio and also get a viable html page from it. I guess the problem is somehow that the old plot cannot be removed properly.
I use rCharts v. 0.4.5 and shiny 0.10.2.1 and I have uploaded an example shiny app to github:
https://github.com/mlist/highcharts_scatterplot_example
As extra dependency you will need to install the packages rjson and foreach. You can then run the app with
runGitHub(repo="mlist/highcharts_scatterplot_example")
```
Use renderChart2 rather then renderChart. Replace output$testPlot with :
output$testPlot <- renderChart2({
p <- highcharts.scatterplot.plate(data.frame(seq(1:nrow(iris)),iris[,2], input$error, iris[,5]))
return(p)
})
You can try the change at:
shiny::runGitHub(repo="johndharrison/highcharts_scatterplot_example")

Resources