无法实现 for 和 while 循环以及如何添加要在选项卡面板中显示的多个输出
Having trouble implementing a for and while loop and how to add multiple outputs to be displayed in a tab panel
我目前正在为一个项目创建一个 RShiny 网站,该项目对美国的谋杀、袭击和强奸数据进行建模。到目前为止,我已经取得了重大进展,但我遇到了两个问题。
我正在尝试将 for 或 while 循环作为我项目的一部分,但我无法在 运行 应用程序时显示输出。我希望 for/while 循环到 return 也具有 Low/Medium/High 犯罪风险的州,其形式为文本“具有 low/medium/high 犯罪率的其他州是 State1、State2、State3 等”。这取决于用户在侧边栏的下拉框中选择的状态。我没有运气为此编写代码。我知道有 100% 更简单的方法可以在没有循环结构的情况下执行此操作,但我的项目要求我使用 for 或 while 循环。
如何在选项卡面板上合并多个输出,以便同时显示两个输出。我希望只有一个“国家有多安全?”选项卡,但每当我尝试将两者结合时,选项卡上不会显示任何输出。
library(shiny)
library(tidyverse)
library(ggplot2)
# Define UI for application that draws the graphs
ui <- fluidPage(
# Application title
titlePanel("Rate of Crime in United States"),
p("Use the variable selector to refine your search!"),
# Sidebar with widgets adjust server output
sidebarLayout(
sidebarPanel(
checkboxGroupInput("display_var",
"Which Crime/s to Display?",
choices = c("Murder" = "Murder",
"Assault" = "Assault",
"Rape" = "Rape"),
selected = "Murder"
),
sliderInput("bins",
"Number of bins (valid for Histogram chart only):",
min = 5,
max = 10,
value = 7
),
selectInput(
"search", "How safe is this state?", choices = (attributes(USArrests)$row.names), selected = NULL)
),
# Create the tabs
mainPanel(
tabsetPanel(
tabPanel("Bar Plot", plotOutput("barplot")),
tabPanel("Histogram", plotOutput("distPlot")),
tabPanel("How Safe is the State?", textOutput("howsafe")),
tabPanel("How Safe is the State?pt2", textOutput("howsafe2"))
)
)
))
# Define server logic required to draw graphs
server <- function(input, output) {
output$barplot <- renderPlot({
marchoice <- req(input$display_var)
sd <- setdiff(names(USArrests),marchoice)
temp_df <- USArrests
temp_df[,sd] <- 0
counts <- temp_df$Murder + temp_df$Assault + temp_df$Rape
names(counts) <- rownames(temp_df)
barplot(counts,
main="Aggregate Sum of Crime in the United States",
xlab="State",
ylab="Frequency",las=2,col=rgb(0.2,0.4,0.6,0.6))
})
#Transform numeric variables into categorical
CategorisedMAR <- cut(USArrests$Murder + USArrests$Assault + USArrests$Rape, breaks=c(0,150,300,450), labels = c("Low", "Medium", "High"))
names(CategorisedMAR) <- attributes(USArrests)$row.names
st <- reactive(input$search)
output$howsafe <- renderText({
#if-else statement to state risk based on state selection
if (CategorisedMAR[[input$search]] == "Low") {
paste0(st(), " has a low rate of crime")
} else if (CategorisedMAR[[input$search]] == "Medium") {
paste0( st()," has a mid-level rate of crime")
} else if (CategorisedMAR[[input$search]] == "High") {
paste0( st(), " has a high rate of crime")
}
})
output$howsafe2 <- renderText({
for(value in CategorisedMAR) {
if(value == "Low") {
print(value)}
}
})
output$distPlot <- renderPlot({
#Create new data based on the selection
USArrests2 <-
USArrests %>%
select(!!input$display_var) %>%
mutate(cumulative_frequency = rowSums(across(where(is.numeric))))
# Create plot - Show the cumulative frequency
ggplot(USArrests2, aes(cumulative_frequency)) + ggtitle("Histogram of Variable Frequency") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_histogram(bins = input$bins,
fill = rgb(0.2,0.4,0.6,0.6),
colour = "grey30") +
#Create a new label based on what has been selected
xlab(str_c(input$display_var, collapse = " & ")) +
theme_minimal()
})
}
# Run the application
shinyApp(ui = ui, server = server)
这是我到目前为止构建的代码。为了清楚起见,我还附上了一张照片,详细说明了我要实现的目标。
"reprex of what I am trying to achieve
我花了无数天的时间来解决这个问题,我们将不胜感激任何帮助。提前致谢!
也许这样就可以了
library(shiny)
library(tidyverse)
library(ggplot2)
library(DT)
# Define UI for application that draws the graphs
ui <- fluidPage(
# Application title
titlePanel("Rate of Crime in United States"),
p("Use the variable selector to refine your search!"),
# Sidebar with widgets adjust server output
sidebarLayout(
sidebarPanel(
checkboxGroupInput("display_var",
"Which Crime/s to Display?",
choices = c("Murder" = "Murder",
"Assault" = "Assault",
"Rape" = "Rape"),
selected = "Murder"
),
sliderInput("bins",
"Number of bins (valid for Histogram chart only):",
min = 5,
max = 10,
value = 7
),
selectInput( "search", "How safe is this state?", choices = (attributes(USArrests)$row.names), selected = NULL)
),
# Create the tabs
mainPanel(
tabsetPanel(
tabPanel("Bar Plot", plotOutput("barplot")),
tabPanel("Histogram", plotOutput("distPlot")),
tabPanel("How Safe is the State?", textOutput("howsafe"), br(),br(), textOutput("howsafe2"))
)
)
))
# Define server logic required to draw graphs
server <- function(input, output) {
output$barplot <- renderPlot({
marchoice <- req(input$display_var)
sd <- setdiff(names(USArrests),marchoice)
temp_df <- USArrests
temp_df[,sd] <- 0
counts <- temp_df$Murder + temp_df$Assault + temp_df$Rape
names(counts) <- rownames(temp_df)
barplot(counts,
main="Aggregate Sum of Crime in the United States",
xlab="State",
ylab="Frequency",las=2,col=rgb(0.2,0.4,0.6,0.6))
})
#Transform numeric variables into categorical
labels = c("Low", "Medium", "High")
CategorisedMAR <- cut(USArrests$Murder + USArrests$Assault + USArrests$Rape, breaks=c(0,150,300,450), labels = labels)
names(CategorisedMAR) <- attributes(USArrests)$row.names
st <- reactive(input$search)
output$howsafe <- renderText({
#if-else statement to state risk based on state selection
if (CategorisedMAR[[input$search]] == "Low") {
paste0(st(), " has a low rate of crime")
} else if (CategorisedMAR[[input$search]] == "Medium") {
paste0( st()," has a mid-level rate of crime")
} else if (CategorisedMAR[[input$search]] == "High") {
paste0( st(), " has a high rate of crime")
}
})
output$howsafe2 <- renderText({
myvalue = CategorisedMAR[[input$search]]
n <- length(CategorisedMAR)
list_states <- c()
for (i in 1:n){
if (CategorisedMAR[[i]]==myvalue) list_states <- c(list_states,names(CategorisedMAR)[i])
}
mylist <- list_states[! list_states %in% st()]
a <- paste0(c("The following states also had", tolower(labels[myvalue]),"rate of crime:"), collapse=" ")
b <- paste0(paste(c(a,mylist), collapse=", "),".")
aa <- gsub(":,",":", b)
paste(aa)
})
output$distPlot <- renderPlot({
#Create new data based on the selection
USArrests2 <-
USArrests %>%
dplyr::select(input$display_var) %>%
mutate(cumulative_frequency = rowSums(across(where(is.numeric))))
# Create plot - Show the cumulative frequency
ggplot(USArrests2, aes(cumulative_frequency)) + ggtitle("Histogram of Variable Frequency") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_histogram(bins = input$bins,
fill = rgb(0.2,0.4,0.6,0.6),
colour = "grey30") +
#Create a new label based on what has been selected
xlab(str_c(input$display_var, collapse = " & ")) +
theme_minimal()
})
}
# Run the application
shinyApp(ui = ui, server = server)
我目前正在为一个项目创建一个 RShiny 网站,该项目对美国的谋杀、袭击和强奸数据进行建模。到目前为止,我已经取得了重大进展,但我遇到了两个问题。
我正在尝试将 for 或 while 循环作为我项目的一部分,但我无法在 运行 应用程序时显示输出。我希望 for/while 循环到 return 也具有 Low/Medium/High 犯罪风险的州,其形式为文本“具有 low/medium/high 犯罪率的其他州是 State1、State2、State3 等”。这取决于用户在侧边栏的下拉框中选择的状态。我没有运气为此编写代码。我知道有 100% 更简单的方法可以在没有循环结构的情况下执行此操作,但我的项目要求我使用 for 或 while 循环。
如何在选项卡面板上合并多个输出,以便同时显示两个输出。我希望只有一个“国家有多安全?”选项卡,但每当我尝试将两者结合时,选项卡上不会显示任何输出。
library(shiny)
library(tidyverse)
library(ggplot2)
# Define UI for application that draws the graphs
ui <- fluidPage(
# Application title
titlePanel("Rate of Crime in United States"),
p("Use the variable selector to refine your search!"),
# Sidebar with widgets adjust server output
sidebarLayout(
sidebarPanel(
checkboxGroupInput("display_var",
"Which Crime/s to Display?",
choices = c("Murder" = "Murder",
"Assault" = "Assault",
"Rape" = "Rape"),
selected = "Murder"
),
sliderInput("bins",
"Number of bins (valid for Histogram chart only):",
min = 5,
max = 10,
value = 7
),
selectInput(
"search", "How safe is this state?", choices = (attributes(USArrests)$row.names), selected = NULL)
),
# Create the tabs
mainPanel(
tabsetPanel(
tabPanel("Bar Plot", plotOutput("barplot")),
tabPanel("Histogram", plotOutput("distPlot")),
tabPanel("How Safe is the State?", textOutput("howsafe")),
tabPanel("How Safe is the State?pt2", textOutput("howsafe2"))
)
)
))
# Define server logic required to draw graphs
server <- function(input, output) {
output$barplot <- renderPlot({
marchoice <- req(input$display_var)
sd <- setdiff(names(USArrests),marchoice)
temp_df <- USArrests
temp_df[,sd] <- 0
counts <- temp_df$Murder + temp_df$Assault + temp_df$Rape
names(counts) <- rownames(temp_df)
barplot(counts,
main="Aggregate Sum of Crime in the United States",
xlab="State",
ylab="Frequency",las=2,col=rgb(0.2,0.4,0.6,0.6))
})
#Transform numeric variables into categorical
CategorisedMAR <- cut(USArrests$Murder + USArrests$Assault + USArrests$Rape, breaks=c(0,150,300,450), labels = c("Low", "Medium", "High"))
names(CategorisedMAR) <- attributes(USArrests)$row.names
st <- reactive(input$search)
output$howsafe <- renderText({
#if-else statement to state risk based on state selection
if (CategorisedMAR[[input$search]] == "Low") {
paste0(st(), " has a low rate of crime")
} else if (CategorisedMAR[[input$search]] == "Medium") {
paste0( st()," has a mid-level rate of crime")
} else if (CategorisedMAR[[input$search]] == "High") {
paste0( st(), " has a high rate of crime")
}
})
output$howsafe2 <- renderText({
for(value in CategorisedMAR) {
if(value == "Low") {
print(value)}
}
})
output$distPlot <- renderPlot({
#Create new data based on the selection
USArrests2 <-
USArrests %>%
select(!!input$display_var) %>%
mutate(cumulative_frequency = rowSums(across(where(is.numeric))))
# Create plot - Show the cumulative frequency
ggplot(USArrests2, aes(cumulative_frequency)) + ggtitle("Histogram of Variable Frequency") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_histogram(bins = input$bins,
fill = rgb(0.2,0.4,0.6,0.6),
colour = "grey30") +
#Create a new label based on what has been selected
xlab(str_c(input$display_var, collapse = " & ")) +
theme_minimal()
})
}
# Run the application
shinyApp(ui = ui, server = server)
这是我到目前为止构建的代码。为了清楚起见,我还附上了一张照片,详细说明了我要实现的目标。 "reprex of what I am trying to achieve
我花了无数天的时间来解决这个问题,我们将不胜感激任何帮助。提前致谢!
也许这样就可以了
library(shiny)
library(tidyverse)
library(ggplot2)
library(DT)
# Define UI for application that draws the graphs
ui <- fluidPage(
# Application title
titlePanel("Rate of Crime in United States"),
p("Use the variable selector to refine your search!"),
# Sidebar with widgets adjust server output
sidebarLayout(
sidebarPanel(
checkboxGroupInput("display_var",
"Which Crime/s to Display?",
choices = c("Murder" = "Murder",
"Assault" = "Assault",
"Rape" = "Rape"),
selected = "Murder"
),
sliderInput("bins",
"Number of bins (valid for Histogram chart only):",
min = 5,
max = 10,
value = 7
),
selectInput( "search", "How safe is this state?", choices = (attributes(USArrests)$row.names), selected = NULL)
),
# Create the tabs
mainPanel(
tabsetPanel(
tabPanel("Bar Plot", plotOutput("barplot")),
tabPanel("Histogram", plotOutput("distPlot")),
tabPanel("How Safe is the State?", textOutput("howsafe"), br(),br(), textOutput("howsafe2"))
)
)
))
# Define server logic required to draw graphs
server <- function(input, output) {
output$barplot <- renderPlot({
marchoice <- req(input$display_var)
sd <- setdiff(names(USArrests),marchoice)
temp_df <- USArrests
temp_df[,sd] <- 0
counts <- temp_df$Murder + temp_df$Assault + temp_df$Rape
names(counts) <- rownames(temp_df)
barplot(counts,
main="Aggregate Sum of Crime in the United States",
xlab="State",
ylab="Frequency",las=2,col=rgb(0.2,0.4,0.6,0.6))
})
#Transform numeric variables into categorical
labels = c("Low", "Medium", "High")
CategorisedMAR <- cut(USArrests$Murder + USArrests$Assault + USArrests$Rape, breaks=c(0,150,300,450), labels = labels)
names(CategorisedMAR) <- attributes(USArrests)$row.names
st <- reactive(input$search)
output$howsafe <- renderText({
#if-else statement to state risk based on state selection
if (CategorisedMAR[[input$search]] == "Low") {
paste0(st(), " has a low rate of crime")
} else if (CategorisedMAR[[input$search]] == "Medium") {
paste0( st()," has a mid-level rate of crime")
} else if (CategorisedMAR[[input$search]] == "High") {
paste0( st(), " has a high rate of crime")
}
})
output$howsafe2 <- renderText({
myvalue = CategorisedMAR[[input$search]]
n <- length(CategorisedMAR)
list_states <- c()
for (i in 1:n){
if (CategorisedMAR[[i]]==myvalue) list_states <- c(list_states,names(CategorisedMAR)[i])
}
mylist <- list_states[! list_states %in% st()]
a <- paste0(c("The following states also had", tolower(labels[myvalue]),"rate of crime:"), collapse=" ")
b <- paste0(paste(c(a,mylist), collapse=", "),".")
aa <- gsub(":,",":", b)
paste(aa)
})
output$distPlot <- renderPlot({
#Create new data based on the selection
USArrests2 <-
USArrests %>%
dplyr::select(input$display_var) %>%
mutate(cumulative_frequency = rowSums(across(where(is.numeric))))
# Create plot - Show the cumulative frequency
ggplot(USArrests2, aes(cumulative_frequency)) + ggtitle("Histogram of Variable Frequency") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_histogram(bins = input$bins,
fill = rgb(0.2,0.4,0.6,0.6),
colour = "grey30") +
#Create a new label based on what has been selected
xlab(str_c(input$display_var, collapse = " & ")) +
theme_minimal()
})
}
# Run the application
shinyApp(ui = ui, server = server)