Matching Parent/Child data up in a DataTable in R Shiny app

戏子无情 提交于 2021-01-29 09:22:31

问题


I have two dataframes; markets is the parent row and mix_breakout is the child table. Each parent row has their own unique child table. I am trying to only have the mix_breakout data that is unique to the parent markets show up in the nested table. For example, the parent row that has the market ABILENE-SWEETWATER should only show data from the same market in mix_breakout.

There also can be an arbitrary number of market / mix_breakout here. This example shows 2 combos, but there can be up to 50 or so.

This is what I have so far.

Data

Parent
structure(list(Market = c("ABILENE-SWEETWATER", "ALBANY-SCHENECTADY-TROY, NY"
), `Gross CPP` = c("$24.65", "$99.05"), `Gross CPM` = c("$12.98", 
"$10.34"), `Historical Composite Gross CPP (if applicable)` = c("$0", 
"$0"), `Historical Composite Gross CPM (if applicable)` = c("$0", 
"$0")), .Names = c("Market", "Gross CPP", "Gross CPM", "Historical Composite Gross CPP (if applicable)", 
"Historical Composite Gross CPM (if applicable)"), row.names = c(NA, 
-2L), class = "data.frame")

Child
structure(list(Market = c("ABILENE-SWEETWATER", "ABILENE-SWEETWATER", 
"ABILENE-SWEETWATER", "ABILENE-SWEETWATER", "ABILENE-SWEETWATER", 
"ABILENE-SWEETWATER", "ABILENE-SWEETWATER", "ABILENE-SWEETWATER", 
"ALBANY-SCHENECTADY-TROY, NY", "ALBANY-SCHENECTADY-TROY, NY", 
"ALBANY-SCHENECTADY-TROY, NY", "ALBANY-SCHENECTADY-TROY, NY", 
"ALBANY-SCHENECTADY-TROY, NY", "ALBANY-SCHENECTADY-TROY, NY", 
"ALBANY-SCHENECTADY-TROY, NY", "ALBANY-SCHENECTADY-TROY, NY"), 
    Daypart = c("Daytime", "Early Fringe", "Early Morning", "Early News", 
    "Late Fringe", "Late News", "Prime Access", "Prime Time", 
    "Daytime", "Early Fringe", "Early Morning", "Early News", 
    "Late Fringe", "Late News", "Prime Access", "Prime Time"), 
    `Share (%)` = c(15, 15, 15, 15, 10, 10, 10, 10, 15, 15, 15, 
    15, 10, 10, 10, 10), `Spot:30 (%)` = c(15, 15, 15, 15, 10, 
    10, 10, 10, 15, 15, 15, 15, 10, 10, 10, 10), `Gross CPP ($)` = c(0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `Gross CPM ($)` = c(18, 
    18, 16, 23, 24, 40, 26, 44, 77, 71, 61, 78, 109, 145, 93, 
    213), GrossCPM = c(1.57, 1.57, 1.39, 2, 2.09, 3.49, 2.27, 
    3.83, 6.71, 6.19, 5.32, 6.8, 9.5, 12.63, 8.1, 18.56)), .Names = c("Market", 
"Daypart", "Share (%)", "Spot:30 (%)", "Gross CPP ($)", "Gross CPM ($)", 
"GrossCPM"), row.names = c(NA, -16L), class = "data.frame")

Code

# The datatable callback
parentRows <- which(Dat[,1] != "")
callback_js = JS(
  "function onUpdate(updatedCell, updatedRow, oldValue) {};",
  sprintf("var parentRows = [%s];", toString(parentRows-1)),
  sprintf("var j0 = %d;", colIdx),
  "var nrows = table.rows().count();",
  "for(var i=0; i < nrows; ++i){",
  "  if(parentRows.indexOf(i) > -1){",
  "    table.cell(i,j0).nodes().to$().css({cursor: 'pointer'});",
  "  }else{",
  "    table.cell(i,j0).nodes().to$().removeClass('details-control');",
  "  }",
  "}",
  "",
  "// make the table header of the nested table",
  "var format = function(d, childId){",
  "  if(d != null){",
  "    var html = ",
  "      '<table class=\"display compact hover\" ' + ",
  "      'style=\"padding-left: 30px;\" id=\"' + childId + '\"><thead><tr>';",
  "    for(var key in d[d.length-1][0]){",
  "      html += '<th>' + key + '</th>';",
  "    }",
  "    html += '</tr></thead><tfoot><tr>'",
  "    for(var key in d[d.length-1][0]){",
  "      html += '<th></th>';",
  "    }",
  "    return html + '</tr></tfoot></table>';",
  "  } else {",
  "    return '';",
  "  }",
  "};",
  "",
  "// row callback to style the rows of the child tables",
  "var rowCallback = function(row, dat, displayNum, index){",
  "  if($(row).hasClass('odd')){",
  "    $(row).css('background-color', 'white');",
  "    $(row).hover(function(){",
  "      $(this).css('background-color', 'lightgreen');",
  "    }, function() {",
  "      $(this).css('background-color', 'white');",
  "    });",
  "  } else {",
  "    $(row).css('background-color', 'white');",
  "    $(row).hover(function(){",
  "      $(this).css('background-color', 'lightblue');",
  "    }, function() {",
  "      $(this).css('background-color', 'white');",
  "    });",
  "  }",
  "};",
  "",
  "// header callback to style the header of the child tables",
  "var headerCallback = function(thead, data, start, end, display){",
  "  $('th', thead).css({",
  "    'border-top': '3px solid green',",
  "    'color': 'black',",
  "    'background-color': 'white'",
  "  });",
  "};",
  "",
  "// make the datatable",
  "var format_datatable = function(d, childId, rowIdx){",
  "  // footer callback to display the totals",
  "  // and update the parent row",
  "  var footerCallback = function(tfoot, data, start, end, display){",
  "    $('th', tfoot).css('background-color', '#fed8b1');",
  "    var api = this.api();",
  "    api.columns().eq(0).each(function(index){",
  "      if(index == 0) return $(api.column(index).footer()).html('Total');",
  "      var coldata = api.column(index).data();",
  "      var total = coldata",
  "          .reduce(function(a, b){return parseFloat(a) + parseFloat(b)}, 0);",
  "      if(index == 4 || index == 5) {",
  "        $(api.column(index).footer()).html((total / coldata.count()).toFixed(2));",
  "      } else {",
  "        $(api.column(index).footer()).html(total);",
  "     }",
  "    })",
  "    var col_share = api.column(1).data();",
  "    var col_CPP = api.column(4).data();",
  "    var col_CPM = api.column(5).data();",
  "    var CPP = 0, CPM = 0;",
  "    for(var i = 0; i < col_share.length; i++){",
  "      CPP += (parseFloat(col_share[i])*parseFloat(col_CPP[i]).toFixed(2));",
  "      CPM += (parseFloat(col_share[i])*parseFloat(col_CPM[i]).toFixed(2));",
  "    }",
  "    table.cell(rowIdx, j0+2).data((CPP/100).toFixed(2));",
  "    table.cell(rowIdx, j0+3).data((CPM/100).toFixed(2));",
  "  }",
  "  var dataset = [];",
  "  var n = d.length - 1;",
  "  for(var i = 0; i < d[n].length; i++){",
  "    var datarow = $.map(d[n][i], function (value, index) {",
  "      return [value];",
  "    });",
  "    dataset.push(datarow);",
  "  }",
  "  var id = 'table#' + childId;",
  "  if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
  "    var subtable = $(id).DataTable({",
  "                 'data': dataset,",
  "                 'autoWidth': true,",
  "                 'deferRender': true,",
  "                 'info': false,",
  "                 'lengthChange': false,",
  "                 'ordering': d[n].length > 1,",
  "                 'order': [],",
  "                 'paging': false,",
  "                 'scrollX': false,",
  "                 'scrollY': false,",
  "                 'searching': false,",
  "                 'sortClasses': false,",
  "                 'rowCallback': rowCallback,",
  "                 'headerCallback': headerCallback,",
  "                 'footerCallback': footerCallback,",
  "                 'columnDefs': [{targets: '_all', className: 'dt-center'}]",
  "               });",
  "  } else {",
  "    var subtable = $(id).DataTable({",
  "            'data': dataset,",
  "            'autoWidth': true,",
  "            'deferRender': true,",
  "            'info': false,",
  "            'lengthChange': false,",
  "            'ordering': d[n].length > 1,",
  "            'order': [],",
  "            'paging': false,",
  "            'scrollX': false,",
  "            'scrollY': false,",
  "            'searching': false,",
  "            'sortClasses': false,",
  "            'rowCallback': rowCallback,",
  "            'headerCallback': headerCallback,",
  "            'footerCallback': footerCallback,",
  "            'columnDefs': [",
  "              {targets: -1, visible: false},",
  "              {targets: 0, orderable: false, className: 'details-control'},",
  "              {targets: '_all', className: 'dt-center'}",
  "             ]",
  "          }).column(0).nodes().to$().css({cursor: 'pointer'});",
  "  }",
  "  subtable.MakeCellsEditable({",
  "    onUpdate: onUpdate,",
  "    inputCss: 'my-input-class',",
  "    columns: [2],",
  "    confirmationButton: {",
  "      confirmCss: 'my-confirm-class',",
  "      cancelCss: 'my-cancel-class'",
  "    }",
  "  });",
  "};",
  "",
  "// display the child table on click",
  "table.on('click', 'td.details-control', function(){",
  "  var tbl = $(this).closest('table'),",
  "      tblId = tbl.attr('id'),",
  "      td = $(this),",
  "      row = $(tbl).DataTable().row(td.closest('tr')),",
  "      rowIdx = row.index();",
  "  if(row.child.isShown()){",
  "    row.child.hide();",
  "    td.html('&oplus;');",
  "  } else {",
  "    var childId = tblId + '-child-' + rowIdx;",
  "    row.child(format(row.data(), childId)).show();",
  "    td.html('&CircleMinus;');",
  "    format_datatable(row.data(), childId, rowIdx);",
  "  }",
  "});")

# Module to create the nested structure of the table
NestedData <- function(dat, children){
  stopifnot(length(children) == nrow(dat))
  g <- function(d){
    if(is.data.frame(d)){
      purrr::transpose(d)
    }else{
      purrr::transpose(NestedData(d[[1]], children = d$children))
    }
  }
  subdats <- lapply(children, g)
  oplus <- sapply(subdats, function(x) if(length(x)) "&oplus;" else "")
  cbind(" " = oplus, dat, "_details" = I(subdats), stringsAsFactors = FALSE)
}

    market_mix_table <- reactive({
      markets <- market_costings_gross_net()
      mix_breakout <- daypart_break_out()

      print(dput(markets))
      print(dput(mix_breakout))

      # Make the dataframe
      # This must be met length(children) == nrow(dat)
      Dat <- NestedData(
        dat = markets,
        children = list(mix_breakout, mix_breakout)
      )
      return(Dat)
    })
# Render the table
    output$daypartTable <- DT::renderDataTable({
      # Whether to show row names (set TRUE or FALSE)
      rowNames <- FALSE
      colIdx <- as.integer(rowNames)
      # The data
      Dat <- market_mix_table()
      # Table
      table <- DT::datatable(
        Dat,
        callback = callback_js,
        rownames = rowNames,
        escape = -colIdx-1,
          options = list(
            columnDefs = list(
              list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
              list(orderable = FALSE, className = 'details-control', targets = colIdx),
              list(className = "dt-center", targets = "_all")
            )
          )
        )
      # Some faancy Java magic
      path <- getwd()
      # Call the html tools deps (js & css files in this directory)
      dep <- htmltools::htmlDependency(
        "CellEdit", "1.0.19", path,
        script = "dataTables.cellEdit.js", stylesheet = "dataTables.cellEdit.css")
      table$dependencies <- c(table$dependencies, list(dep))
      # server = FALSE
      return(table)
    })

Thanks for the help!!

来源:https://stackoverflow.com/questions/60838658/matching-parent-child-data-up-in-a-datatable-in-r-shiny-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!