jbkunst / highcharter

R wrapper for highcharts
http://jkunst.com/highcharter/
Other
720 stars 149 forks source link

Problems handling data of length 1? #65

Closed joh024 closed 8 years ago

joh024 commented 8 years ago

The following, with data of length 1, does not work:

highchart() %>% hc_chart(type = "bar") %>% hc_add_series(data = 1)

The following, with data of length 2, does work:

highchart() %>% hc_chart(type = "bar") %>% hc_add_series(data = 1:2)

However we can see from this JSFiddle, that Highcharts itself should be able to handle data of length 1, provided it is an array of length 1. So I suspect what's happening is that when the data is of length 1, highcharter is not exporting it as an array.

jbkunst commented 8 years ago

Hi @joh024

Under the hood, htmlwidgets uses jsonlite to convert the r list into javascript object. By default htmlwidgets set auto_unbox = TRUE so the 1 length atomic elements are not send as array. According the jsonlite documentation:

auto_unbox automatically unbox all atomic vectors of length 1. It is usually safer to avoid this and instead use the unbox function to unbox individual elements.

> library("jsonlite")
> 
> toJSON(list(x = 1), auto_unbox = TRUE)
{"x":1} 
> toJSON(list(x = c(1, 2)), auto_unbox = TRUE)
{"x":[1,2]} 
> toJSON(list(x = list(1)), auto_unbox = TRUE)
{"x":[1]} 

You have 2 quick fixs/solutions:

#1
highchart() %>% hc_chart(type = "bar") %>% hc_add_series(data = list(1))

# 2
options(htmlwidgets.TOJSON_ARGS = list(auto_unbox = FALSE))
highchart() %>% hc_chart(type = "bar") %>% hc_add_series(data = 1)

Not sure if I need to change the dafaults in the package. If you're agree we can close the issue.

Thanks for this issue and for use the package.

joh024 commented 8 years ago

Ah, I see. That works for me, thanks for the quick reply.