I'm trying to understand how an R data frame is passed to a d3.js script using the package r2d3. An extension of the r2d3 bar chart example to access variables in data.frame object would be helpful.
R code:
library(r2d3)
data <- data.frame(nums = c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20))
r2d3(data, script = "test.js")
js code:
var barHeight = Math.floor(height / data.length);
svg.selectAll('rect')
.data(data.nums)
.enter().append('rect')
.attr('width', function(d) { return d * width; })
.attr('height', barHeight)
.attr('y', function(d, i) { return i * barHeight; })
.attr('fill', 'steelblue');
Error:
Error: svg.selectAll(...).data(...).enter is not a function in (test.js#5:4)
TypeError: svg.selectAll(...).data(...).enter is not a function
This error occurs because
data.numsis undefined.Your
datavariable is not an object containing an array as follows:But, rather an array containing objects:
To keep you
rside code, we just need to pass the data array itself toselection.data()and access thenumsproperty of each datum: