|
- ---
- pagetitle: Prepare Data for htmlwidget
- example:
- title: Prepare Data for htmlwidget
- instructions: |-
- An R list has been converted to JSON for use in an htmlwidget, but the `.data` property is still in "R" format.
- Assume that the first key (column) should be used as `labels` and the remaining columns should be used as the `datasets`.
-
- Reformat the data to follow the pattern in the example below and replace the `x.data` property.
- hint: |-
- ```js
- x.data = {
- labels: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
- datasets: [
- { name: "R", values: [18, 40, 30, 35, 8, 52, 17, -4] },
- { name: "Python", values: [30, 50, -10, 15, 18, 32, 27, 14] }
- ]
- }
- ```
- runtime: repl
- mode:
- document: html
- initial:
- js: |-
- let x = document.getElementById('chart-opts')
- x = JSON.parse(x.textContent)
-
- // create an empty object to hold the formatted chart data
- const chartData = {labels: [], datasets: []}
-
- // Get keys of data, assume that first entry is for labels, the rest are data
- // chartData.labels = ...
-
- // Create an appropriate object for each column, reformat data and add to chartData
-
- x.data = chartData
- css: ~
- solution:
- js: |-
- let x = document.getElementById('chart-opts')
- x = JSON.parse(x.textContent)
-
- // create an empty object to hold the formatted chart data
- const chartData = {labels: [], datasets: []}
-
- // Get keys of data, assume that first entry is for labels, the rest are data
- let labelColumn = Object.keys(x.data)[0]
- let columns = Object.keys(x.data).slice(1)
-
- console.log({labelColumn, columns})
-
- // First column in x.data is the labels
- chartData.labels = x.data[labelColumn]
-
- // Create an appropriate object for each column, reformat data and add to chartData
- columns.forEach(function(col) {
- chartData.datasets.push({name: col, values: x.data[col]})
- })
-
- x.data = chartData
- css: ~
- output: js4shiny::html_document_js4shiny
-
- ---
- <div><!--for pandoc-->
- <script id="chart-opts" type="application/json">{"title":"My AwesomeR Chart","type":"line","height":250,"colors":["#466683","#44bc96"],"data":{"year":[1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017],"August":[149,137,130,135,142,146,155,145,147,181,169,183,194,211,255,327,316,377,425,368,409,387,378,376,375,431,470,512,690,760,758,837,1077,1170,1769,2331,2313,2295],"Ruth":[1262,1272,1193,1135,1174,1125,1096,1040,1012,997,913,990,853,863,880,858,801,856,850,870,903,943,900,888,905,906,889,958,929,912,929,901,926,986,1057,1102,1094,1194]},"lineOptions":{"regionFill":true,"hideDots":false},"axisOptions":{"xIsSeries":true},"isNavigable":true}</script>
- </div><!--for pandoc-->
|