Mickey_NC - 1 year ago 61

R Question

I'm a beginner on R and Shiny and I have a little problem.

If you could help please, I would really appreciate.

For example, I've added the variable Group to the R data frame "mtcars" in characters format. Now I have 3 groups of cars : 1, 2 and 3, depending on the "mpg" level of each car.

I would like one renderText which shows the number of cars of the group(s) I have checked, a second one to show the number of 4cylinders cars of the checked group(s), a third one to show the number of 6cylinders cars, and a fourth one to show the number of 6cylinders cars.

If I keep only the Group textRender, it works great, but when I add the 3 others, there's an error and I don't find why.

This is the code :

ui.R

`library(shiny)`

shinyUI(pageWithSidebar(

headerPanel("Example"),

sidebarPanel(checkboxGroupInput("dynamic", "Groups", label = "Groups",

choices = c("Group 1"="1","Group 2"="2","Group 3" = "3"))),

mainPanel(("Group : "), textOutput("textDisplay"),

("4 cylinders : "), textOutput("text4cyl"),

("6 cylinders : "), textOutput("text6cyl"),

("8 cylinders : "), textOutput("text8cyl"))))

server.R

`library(shiny)`

shinyServer(function(input, output) {

output$textDisplay <- renderText({

a<-sum(mtcars$Group %in% input$dynamic)

output$text4cyl <- renderText({

b<-sum(mtcars$Group %in% input$dynamic) & mtcars$cyl ==4

output$text6cyl <- renderText({

c<-sum(mtcars$Group %in% input$dynamic) & mtcars$cyl ==6

output$text8cyl <- renderText({

d<-sum(mtcars$Group %in% input$dynamic) & mtcars$cyl ==8})})})})})

Thank you very very much for help, and sorry for my English.

Answer Source

I have just created the groupings which are probably different than yours. This is one possible solution:

ui.R

```
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Example"),
sidebarPanel(checkboxGroupInput("dynamic", "Groups", label = "Groups",
choices = c("Group 1"="1","Group 2"="2","Group 3" = "3"))),
mainPanel(("Group : "), textOutput("textDisplay"),
("4 cylinders : "), textOutput("text4cyl"),
("6 cylinders : "), textOutput("text6cyl"),
("8 cylinders : "), textOutput("text8cyl"))))
```

server.R

```
library(shiny)
library(dplyr)
group <- c(rep("1", 11), rep("2", 11), rep("3", 10))
group
mtcars$Group<-factor(group)
shinyServer(function(input, output) {
selection <- reactive({
filter(mtcars, Group %in% input$dynamic)
})
output$textDisplay <- renderText({
NROW(selection())
})
output$text4cyl <- renderText({
tmp <- selection()
NROW(filter(tmp, cyl == 4))
})
output$text6cyl <- renderText({
tmp <- selection()
NROW(filter(tmp, cyl == 6))
})
output$text8cyl <- renderText({
tmp <- selection()
NROW(filter(tmp, cyl == 8))
})
})
```