我有一个简单的Shiny应用程序,可以打印数据集的正态分布。它使用selectInput允许用户更改他们希望看到绘制的数据集。这部分应用程序是有效的。我想在renderPlot下添加一个renderText部分,根据用户的选择显示平均值和标准差,但是没有文本显示在应用程序上。相反,当我希望它在实际的Shiny应用程序中显示在情节下面时,我的文本被输出到控制台。
到目前为止,这是我的服务器代码。R:
# This application will allow the user to view the standard normal distribution for multiple different datasets
# This app demonstrates use of the selectInput and submitButton features available in Shiny
library(shiny)
library(dplyr)
# Cars dataset
data("mtcars")
x_cars <- mtcars$mpg
avg_cars <- mean(x_cars)
stdev_cars <- sd(x_cars)
y_cars <- dnorm(x_cars, avg_cars, stdev_cars)
# PlantGrowth dataset
data("PlantGrowth")
x_plants <- filter(PlantGrowth, group =="ctrl")
x_plants <- select(x_plants, weight)
x_plants <- as.numeric(unlist(x_plants))
avg_plants <- mean(x_plants)
stdev_plants <- sd(x_plants)
y_plants <- dnorm(x_plants, avg_plants, stdev_plants)
# USArrests
data("USArrests")
x_murders <- select(USArrests, Murder)
x_murders <- as.numeric(unlist(x_murders))
avg_murders <- mean(x_murders)
stdev_murders <- sd(x_murders)
y_murders <- dnorm(x_murders, avg_murders, stdev_murders)
# If statements for determining which dataset is the desired output
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
if (input$Dataset == "mtcars") {
plot(x_cars,y_cars,main="Average mpg of all cars in mtcars dataset", xlab="mpg", ylab="Probability Density")
}
if (input$Dataset == "PlantGrowth") {
plot(x_plants,y_plants,main="Average weight of plants in the control group", xlab="Plant Weight",ylab="Probability Density")
}
if (input$Dataset == "USArrests") {
plot(x_murders,y_murders,main="Number of murders by US state", xlab="Murder Count", ylab="Probability Density")
}
})
output$textOut <- renderText({
cat("This simple Shiny app demonstrates usage of the selectInput and submitButton featuresn")
if (input$Dataset == "mtcars") {
cat("Mean: ", avg_cars, "n")
cat("Standard Deviation: ", stdev_cars, "n")
}
if (input$Dataset == "PlantGrowth") {
cat("Mean: ", avg_plants, "n")
cat("Standard Deviation: ", stdev_plants, "n")
}
if (input$Dataset == "USArrests") {
cat("Mean: ", avg_murders, "n")
cat("Standard Deviation: ", stdev_murders, "n")
}
})
})
这是我的ui代码。R:
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput(inputId="Dataset","Dataset",label="Select desired dataset:",choices=c("mtcars","PlantGrowth","USArrests")),
submitButton("Confirm Changes")),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
textOutput("textOut")
)
)
))
不要使用cat()
。你必须在renderText
中返回一个字符串。因此用paste
代替cat