nearPoints gets confused by .data: xvar not in names of input

Viewed 341

The following code does not work:

library(ggplot2)
library(shiny)
shinyApp(ui=fluidPage(
            plotOutput("plot", click="clicked"),
            tableOutput("near")),
         server=function(input, output, session) {
           df <- data.frame(x=rnorm(100), y=rnorm(100))
           output$plot <- renderPlot({
             ggplot(df, aes(x=.data$x, y=.data$y)) + geom_point()
           })

           output$near <- renderTable({
             nearPoints(df, input$clicked)
           })    
         })

When a point on the plot is clicked, following error appears:

nearPoints: `xvar` ('.data$x')  not in names of input

If instead the ggplot statement above, the following statement is used

ggplot(df, aes(x=x, y=y)) + geom_point()

everything works as expected.

The reason why I am using data$x (or data[["x"]], which also gives an error) in aes() is that this code is inside of a package, and data[["x"]] was used to eliminate R package check warnings (as described in programming with dplyr). I could circumvent the problem in the plotting function rather than in the shiny app I am working on (e.g. by defining dummy variables x and y), but first, this is not elegant, and second, what if one day I have a plotting function from another package which uses a similar trick?

My question: how to make the above code work in shiny without modifying the ggplot statement?

1 Answers

You can specify xvar and yvar in the nearPoints function, that is

nearPoints(df, input$clicked, xvar="x", yvar="y")
Related