gpt4 book ai didi

r - 使用 R shiny 切换对象(如表格)

转载 作者:行者123 更新时间:2023-12-04 03:31:40 29 4
gpt4 key购买 nike

我正在尝试制作我的第一个 Shiny 的应用程序,但惨遭失败。我希望能够切换 3 个不同的数据框(并将它们呈现为表格)。我的想法是通过在侧边栏面板中选择它们来在主面板中呈现每个表(A、B、C)。

我是其中的一部分,但在“输出”阶段苦苦挣扎......

library(shiny)
library(dplyr)

A <- data.frame(ID = c("A", "B", "C","D"),
colour = c("red", "white", "blue", "orange"),
age =c("8", "3", "4", "5"))

B <- data.frame(ID = c("Bob", "Bill", "Jack","Dave"),
shape = c("star", "square", "circle", "triangle"),
age =c("15", "12", "13", "14"))

C <- data.frame(ID = c("Jane", "Jenny", "Bex","Sarah"),
animal = c("cat", "dog", "fish", "tiger"),
food =c("chips", "burger", "sushi", "chocolate"))

ui <- fluidPage(
titlePanel("Failing at my first shiny app"),
sidebarLayout(
sidebarPanel(
selectInput("tableInput", "Table",
choices = c("A", "B", "C"))
),
mainPanel(
tableOutput("results")
)
)
)

server <- function(input, output) {

output$results <- renderTable({
#want to toggle through objects here
#how do I do it?!
})
}

shinyApp(ui = ui, server = server)

如果有人能指出正确的方向,我将不胜感激!谢谢!

最佳答案

renderTable中,获取对象的值

get(input$tableInput)

input$tableInput 根据用户选择返回对象名称“A”、“B”、“或 C”。 input 是函数的参数,tableInput 是用户为 Table 输入选择列表定义的名称,该列表存储“A”、“B” ', 'C'选项

get 返回对象的值,即 data.frame

-完整代码

library(shiny)
library(dplyr)

A <- data.frame(ID = c("A", "B", "C","D"),
colour = c("red", "white", "blue", "orange"),
age =c("8", "3", "4", "5"))

B <- data.frame(ID = c("Bob", "Bill", "Jack","Dave"),
shape = c("star", "square", "circle", "triangle"),
age =c("15", "12", "13", "14"))

C <- data.frame(ID = c("Jane", "Jenny", "Bex","Sarah"),
animal = c("cat", "dog", "fish", "tiger"),
food =c("chips", "burger", "sushi", "chocolate"))

ui <- fluidPage(
titlePanel("Failing at my first shiny app"),
sidebarLayout(
sidebarPanel(
selectInput("tableInput", "Table",
choices = c("A", "B", "C"))
),
mainPanel(
tableOutput("results")
)
)
)

server <- function(input, output) {

output$results <- renderTable({
get(input$tableInput)
})
}

shinyApp(ui = ui, server = server)

-输出

enter image description here

关于r - 使用 R shiny 切换对象(如表格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66681020/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com