rd3.jsshinynvd3.js

Understanding and rebuilding overload of a dataframe to d3 format


I am really desperated about a function for a dataframe overload, from R to the nvd3-line-chart. My inteniton is to display a dataframe in R Shiny app using the nvd3 linechart as shown here:

https://shiny.rstudio.com/gallery/nvd3-line-chart-output.html

The main problem is, the X axis is just an incremented number, given by the amount of rows of the overloaded dataframe (as shown in the example above). I Need to have the first column of the dataframe as my x-axis. Therefore I want to Change the Code, actual target is to replace it by r2d3 functions, available in R.

In this example I do not understand the following Things: How is the dataframe overloaded to mentoined function and then to the diagram? Can anyone show me a way to see the output of the conversion function, and replace it by a manually created d3 string to test?

The call of the function:

output$mychart <- renderLineChart({
  df_stocking_catches
})

The function I do not understand.

# To be called from server.R
renderLineChart <- function(expr, env=parent.frame(), quoted=FALSE) {
  # This piece of boilerplate converts the expression `expr` into a
  # function called `func`. It's needed for the RStudio IDE's built-in
  # debugger to work properly on the expression.
  installExprFunction(expr, "func", env, quoted)

  function() {
    dataframe <- func()

    mapply(function(col, name) {

      values <- mapply(function(val, i) {
        list(x = i, y = val)
      }, col, 1:nrow(dataframe), SIMPLIFY=FALSE, USE.NAMES=FALSE)

      list(key = name, values = values)

    }, dataframe, names(dataframe), SIMPLIFY=FALSE, USE.NAMES=FALSE)
  }
}

Thank you for any suggestions. Sam


Solution

  • hurray, got it! It's not pretty but it works exactly as I wanted. Used the debugging function browser() and the print() command to analyze the function step-by-step. I feel like a genious now to have solved by my own, but still do not undertand clearly this crappy piece of code.

    renderLineChart <- function(expr, env=parent.frame(), quoted=FALSE) {
      installExprFunction(expr, "func", env, quoted)
    
      function() {
        dataframe <- func()
    
        mapply(function(col, name) {
          if(name!="Year"){
            values <- mapply(function(val, i) {
              list(x = dataframe[i,1], y = val)
              #browser()
              #print(dataframe[i,1])
            }, col, 1:nrow(dataframe), SIMPLIFY=FALSE, USE.NAMES=FALSE)
            list(key = name, values = values)
    
          }
        }, dataframe[,-1], names(dataframe[,-1]), SIMPLIFY=FALSE, USE.NAMES=FALSE)
      }
    }
    

    Hope anyone gets inspired by this post. Bye