Recently, I try to learning shinyapp, and I try to do a shinyapp for t-test:
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("t test shinyapp"),
# Sidebar set
sidebarLayout(
sidebarPanel(
h4(fileInput("file","Upload the file"),
helpText("Default max. file size is 5MB"),
# Horizontal line ----
tags$hr(),
uiOutput("vx1"),
br(),
uiOutput("vx2"),
br(),
uiOutput("gg"),
br(),
selectInput("method", "Select t test type",
c("One-sample t test",
"Independent two-sample t test",
"Paired sample t test"),
selected = "Independent two-sample t test"),
br(),
selectInput("alt", "Select alternative",
c("two.sided",
"greater",
"less"),
selected = "two.sided"),
br(),
textInput("mu", "Enter population mean for one-sample t test", ""),
br(),
radioButtons("ptype",
"Select the file type",
choices = list("png", "pdf")))),
mainPanel(
uiOutput("tb")
)
)))
shinyServer(function(input, output) {
dff <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
read.csv(file=file1$datapath, header = TRUE)
})
output$vx1 <- renderUI({
selectInput("var1", "Select variable names", choices = names(dff()))
})
output$vx2 <- renderUI({
selectInput("var2", "Select variable names", choices = names(dff()))
})
output$gg <- renderUI({
selectInput("gro", "Select group name", choices = names(dff()))
})
output$sum <- renderTable({
if(is.null(dff())){return ()}
print(c(paste0("You choice to do: ",input$method),
paste0("The way you use to test is: ", input$alt),
paste0("The variable you choice is: ", input$var1),
paste0("The group variable you selected is: ", input$gro),
paste0("the levels of group variable is:", levels(as.factor(dff()[input$gro])))),
sep = "\n")
print(dff()[input$gro])
})
output$tr <- renderTable({
if(is.null(dff())){return ()}
if(input$method == "One-sample t test"){
t.test(dff1[input$var1], mu = as.numeric(input$mu), alternative = input$alt)
} else if(input$method == "Independent two-sample t test"){
t.test(input$var1 ~ input$gro, data = dff(), alternative = input$alt)
}else{
t.test(dff()[input$var1], dff()[input$var2], paired=TRUE, alternative = input$alt)
}
})
output$tplot <- renderPlot({
})
downloadHandler(
filename = function(){
paste(input$method, input$ptype, sep = ".")
},
content = function(){
if(input$ptype == "png")
png(file)
else
pdf(file)
dev.off()
}
)
output$tb <- renderUI({
if(is.null(data()))
h5("Powered by", tags$img(src='qrcode.jpg'))
else
tabsetPanel(tabPanel("Summary", tableOutput("sum")),
tabPanel("t test result", tableOutput("tr")),
tabPanel("Plot",
downloadButton("download", "download the plot"),
))
})
})
As you can see, I can print dff()[input$gro] in output$sum, but I can't run in output$tr.
when I run the code, I get the Erorr: Error in t.test.formula: grouping factor must have exactly 2 levels.
What's the problem. Thank you so much.