h.l.m h.l.m - 3 months ago 25
R Question

R gvisTable pre-selection using event trigger option and Javascript code

In R I am looking to set the selection of the output for a gvisTable so that a specific row or column is highlighted.

For example I have the following code:

a <- as.data.frame(matrix(1:100, nrow=10))


and only until clicking, on say row 4, does it highlight.

Is there a way to preselect row 4 upon running the plot function, i.e. it automatically highlights row 4.

Having looked in the vignette for googleVis, there appears to be an event listener and and event trigger which can have some javascript code inserted into the options so that the output is altered. This was done by using the option gvis.listener.jscode. Is there an an equivalent for the trigger to fire an event. I think the javascript code would need to use something like
but my Javascript knowledge is limited at best and so I am not too sure how to integrate it.

p.s the eventlistener can be found by running



The only way I can figure out to do it is to inject some custom JavaScript into the HTML created by the call to gvisTable(). You won't be able to use the EventListener as the example you provided does -- the reason being that the eventListener, as currently implemented, only gets executed when the table is clicked. You need your code to execute before then. It looks like the best place to insert it, then, is in the jsDrawChart section of the returned HTML. This is where the JS representation of the chart object gets assembled. After drawing the chart, you can then make additional calls to the object.

A quick look at the Google Charts documentation for the table object shows that you have a nice setSelection() function available to you in Javascript, assuming you use the proper parameter format.

I did the following:

mytab <- (gvisTable(a,chartid="myTable"))
#you just want to add the following line of JS before the close bracket in the jsDrawChart function.
# chart.setSelection([{'row':2, 'column':null}]);

#in my case, that turned out to be the following:
mytab$html$chart["jsDrawChart"] <- "\n// jsDrawChart\nfunction drawChartmyTable() {\n  var data = gvisDatamyTable();\n  var options = {};\noptions[\"allowHtml\"] = true;\n\n     var chart = new google.visualization.Table(\n       document.getElementById('myTable')\n     );\n     chart.draw(data,options);\n  chart.setSelection([{'row':2, 'column':null}]);   \n\n}\n  \n"

You could certainly make that a bit more robust by automatically inserting the additional line of JS before the close bracket using RegEx or modifying the source of the GoogleVis function.

But once I've added that line of JS, I'm now able to run plot(mytab) and have it automatically select the row I want (keep in mind that it's 0-indexed).