Utilizing DT::datatable to Display Grouped DataFrame in an Rmarkdown Report (HTML)

I am trying to display a grouped data frame output in an interactive DT::datatable with Download buttons (csv,excel) within my Rmarkdown report (HTML).

Everything works smoothly until I encounter an error stating that there is no group by method applicable for object classes datatable and htmlwidgets.

Your assistance would be greatly appreciated.

Below is the code snippet:

## Grouping columns

Site <- LETTERS[1:6]
Block <- LETTERS[1:4] ## For each Site
Plot <- paste(rep("P",10),seq(1,10,1),sep="_") ## For each Block 
df <- expand.grid(Site = Site, Block = Block, Plot = Plot)

## Dependant variables

df <-cbind.data.frame(df,data.frame(Tmin=runif(min=-3,max=18,n=240),
                         Tmax=runif(min=10,max=39, n=240),
                                    Index1=runif(0,5,n=240),
                                    Index2=runif(1,10,n=240)))

# Export grouped df as datatable
library(dplyr)


df%>%
  group_by(Site,Block,Plot)%>%
  summarize(Tmin_avg=mean(Tmin), Tmax_avg=mean(Tmax))%>%
  DT::datatable(
   extensions = 'Buttons', options = list(
    dom = 'Bfrtip',
    buttons = 
      list('copy', 'print', list(
        extend = 'collection',
        buttons = c('csv', 'excel', 'pdf'),
        text = 'Download'
      ))
   ))

Answer №1

Make sure to aggregate your data properly and remove the ... from the summarize function. The ... in functions allow users to include additional parameters. For example:

library(tidyverse) 

aggdata <- function(df, ...) {
  df%>
    group_by(Site,Block,Plot)%>
    summarize(Tmin_avg=mean(Tmin), Tmax_avg=mean(Tmax), ...)%>
    DT::datatable(
      extensions = 'Buttons', options = list(
        dom = 'Bfrtip',
        buttons = 
          list('copy', 'print', list(
            extend = 'collection',
            buttons = c('csv', 'excel', 'pdf'),
            text = 'Download'
          ))
      ))
}

aggdata(df, T_min = min(Tmin))

To correct your example, make these changes:

df%>
  group_by(Site,Block,Plot)%>
  summarize(Tmin_avg=mean(Tmin), Tmax_avg=mean(Tmax))%>
  DT::datatable(
   extensions = 'Buttons', options = list(
    dom = 'Bfrtip',
    buttons = 
      list('copy', 'print', list(
        extend = 'collection',
        buttons = c('csv', 'excel', 'pdf'),
        text = 'Download'
      ))
   ))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript is limited to functioning within the content area of WordPress websites

Currently, I am using WordPress and I am looking to have my share links follow the post as a user scrolls down. The issue I'm facing is that the JavaScript code is directly attached to content.php, causing it to load multiple times on pages with multi ...

A guide on adjusting a function to pause execution until a line is complete

In the code snippet below, there is an angularJS function named myFunc: $scope.myFunc = () => { myModule.getConfig().update(params); myModule.go(); myModule.log('ok'); }; Additionally, there is a go function defi ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

`Is there a way to sort a deeply nested object by its values?`

I need assistance sorting an array of hospitals based on the lowest value of the amountinINR key, especially when dealing with deeply nested arrays of hospital objects. Does anyone know how to achieve this without using third-party libraries like lodash or ...

What is the best way to delete and add elements in a looped array using Javascript

i have a form similar to this one. https://i.sstatic.net/V7ivb.png how can I replace this form each time the country changes, by removing it and then appending it again from a looping array. If there is only one set of data, display an "Add Form" Button; ...

Is there a way to change the projection of id in mongoose?

I have a microservice in Node.js, where I am using Mongoose to retrieve a document from my mongoDB. The document has multiple properties, but I only need to display 3 of them: The properties I want to display are '_id' as 'id', 'n ...

Is Formik Compatible with TextareaAutosize?

I've implemented react-textarea-autosize and formik in my project, but I'm having trouble connecting the change events of formik to TextareaAutosize. Can anyone guide me on how to do this properly? <Formik initialValues={{ ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

Transferring JavaScript to PHP

I have a challenge where I need to pass a string stored in a variable to a MySQL table using PHP. Currently, my workaround involves using a hidden <input>. I assign the variable value to it and submit it through a form. It works, but it's not e ...

What is the reason for the original list being affected when the cloning list is created using a

I am trying to convert an object inside an array into a string using the code below. However, I can't seem to understand why it's affecting the original array. I thought that 'slice' was supposed to clone the array? var cloned = $scope ...

Determine the global upward direction of an object along any given axis in ThreeJS

I'm struggling to determine the exact rotation of my object around any given axis. Thus far, I've managed to find the relative rotation of my object using a specific method. To achieve this, I positioned a plane behind the object aligned with th ...

Guidelines for preserving regular expression matches in an array with JavaScript

If I have a regex with multiple matches like: var matches = string.match(/\s*(regex1)?\s*(regex2)?(regex3)?\s*/i); and if the string I'm testing looks like this: var string = "regex1 regex3"; Is there a way to capture these values i ...

Transforming substantial quantities of data into a string array in JavaScript

I have around 2000 items of data that I work with on a regular basis in Visual Studio Code. Is there a way to convert this data into a string array without having to manually add quotes around each item using JavaScript? var array = [ a2kjda a2dkj ...

Testing JavaScript performance using the V8 engine

function add(x, y) { return x + y; } console.time("clock1"); for (var i = 0; i < 90000000; ++i) { add(1, 2); add('a','b'); } console.timeEnd("clock1"); function combineText(x, y) { return x + y; } fu ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

Ensuring the preservation of value type while making a Vue component function with v-model

Issue When using v-model on an HTML <select>, the v-model function assigns the selected value while preserving the data types - if a number is bound to an <option>, the model property will also be assigned as a number, and if an Object is boun ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

Hide the dropdown menu when the user clicks anywhere else on the screen

I have a scenario with 2 dropdown buttons. When I click outside the dropdown or on it, it closes. However, if I click on the other dropdown button, it does not close and the other one opens. I want them to close when I click on the other button or anywhere ...

Discover a method for bypassing the Quick Search Firefox feature and capturing the forward slash keypress

Currently, I am trying to capture the key press value of '191' for the forward slash (/) as part of a feature on my website. This functionality works perfectly on all browsers except for Firefox, where it conflicts with the Quick Search feature. ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...