0

I want to change a part of my shiny code in data.table.

dfMktHop1_Z1<-reactive({ZoneHop1.1()%>%
      group_by(codeGeo,Hopital)%>%count()%>%# sejour par commune et par hopital
      ungroup()%>%group_by(codeGeo)%>%add_tally(n,name="sejour.com")%>%# sejour tot commune
      filter(Hopital==input$Hopital1)%>%select(codeGeo,Hopital,n,sejour.com)%>%
      rename(Hopital1=Hopital,Sej.Hop1=n)})

I asked ChatGPT to transform it into data.table : This is what it suggested;

dfMktHop1_Z1 <- reactive({
  data <- ZoneHop1.1()
  
  data_count <- data[, .N, by = .(codeGeo, Hopital)]
  
  data_tally <- data_count[, .(sejour.com = sum(N)), by = codeGeo]
  
  data_filtered <- data_tally[Hopital == input$Hopital1, .(codeGeo, Hopital1 = Hopital, Sej.Hop1 = sejour.com)]
  
  setnames(data_filtered, "codeGeo", "Code")
  
  return(data_filtered)
})

But I encountered an error message with this:

Error in [.data.frame: unused argument (by = .(codeGeo, Hopital))

What's wrong with this code?

user438383
  • 5,716
  • 8
  • 28
  • 43
Seydou GORO
  • 1,147
  • 7
  • 13
  • 5
    From the error message I would guess that you first have to convert `data` to a `data.table` object using e.g. `setDT(data)`. For more help please provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Aug 10 '23 at 10:48

1 Answers1

1

I think this should work:

dfMktHop1_Z1 <- reactive({
  req(ZoneHop1.1())
  as.data.table(ZoneHop1.1()) %>%
    .[, .(n = .N), by = .(codeGeo, Hopital) ] %>%
    .[, sejour.com := .N, by = .(codeGeo) ] %>%
    .[Hopital == input$Hopital1, .(codeGeo, Hopital1 = Hopital, Hop1 = n, sejour.com)]
})

In general,

  • group_by %>% count is equivalent to .[, .(n = .N), by = .(..)]
  • add_tally is similar but just additive, .[, n := .N, by = .(..)]
  • filter is a direct translation

I combined the filter and select into a single expression, seemed to make sense.

I suspect that the cause of your error, as stefan highlighted, is that you are trying this on a data.frame and not a data.table. For demonstration, using either method (as.data.table or setDT):

mtcars[, .(n = .N), by = .(cyl)]
# Error in `[.data.frame`(mtcars, , .(n = .N), by = .(cyl)) : 
#   unused argument (by = .(cyl))
as.data.table(mtcars)[, .(n = .N), by = .(cyl)]
#      cyl     n
#    <num> <int>
# 1:     6     7
# 2:     4    11
# 3:     8    14
MT <- mtcars
setDT(MT)
MT[, .(n = .N), by = .(cyl)]
#      cyl     n
#    <num> <int>
# 1:     6     7
# 2:     4    11
# 3:     8    14
r2evans
  • 141,215
  • 6
  • 77
  • 149