【发布时间】:2021-10-06 04:28:57
【问题描述】:
我正在创建一个应用程序,它从一个目录中获取一个文件并获取列名,让用户有机会决定要使用哪个示例。
我没有上传文件,而是创建了一个数据框(类似于我的文件)并将其放入响应函数中(这正是我通常在上传文件时所做的)。
这是数据框
numbers <- c(5,345,55,10)
df<-data.frame(t(numbers))
names(df) <- c("S1", "S2", "S3", "S4")
> df
S1 S2 S3 S4
1 5 345 55 10
我的应用有一个checkboxInput,您可以决定是否要对数据框进行对数。
如果我想比较 S1 和 S2,我意识到当我不点击进入框(并且我不做对数)时,样本不会改变。这就是我想要的。
但是,如果我决定做对数(我点击复选框)示例 2 更改(现在它比较 S1 和 S1,我不太明白为什么,我不知道不想)。
这是代码:
library(shiny)
# Define UI
ui <- fluidPage(
# Application title
titlePanel("My app"),
sidebarLayout(
sidebarPanel(
uiOutput("selected_sample_one"),
uiOutput("selected_sample_two"),
checkboxInput("change_log2", "Log2 transformation", value = F),
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot")
)
)
)
# Define server
server <- function(input, output,session) {
data <- reactive({
numbers <- c(5,345,55,10)
df<-data.frame(t(numbers))
names(df) <- c("S1", "S2", "S3", "S4")
if(input$change_log2 == TRUE){
df <- log2(df)
}
return(df)
})
samples_names <- reactive({
samples <- colnames(data())
return(samples)
})
output$selected_sample_one <- renderUI({
selectizeInput(inputId = "sample_one_axis", "Select the 1st sample", choices=samples_names(), options=list(maxOptions = length(samples_names())))
})
# With this function you can select which sample do you want to plot in the y-axis.
output$selected_sample_two <- renderUI({
selectizeInput(inputId = "sample_two_axis", "Select the 2nd sample", choices=samples_names(), options=list(maxOptions = length(samples_names())))
})
output$plot <- renderPlot({
barplot(c(data()[,input$sample_one_axis], data()[,input$sample_two_axis]))
})
}
# Run the application
shinyApp(ui = ui, server = server)
注意:
如果我将列名保存到向量中,对数和一切都有效。 而不是使用
samples_names <- reactive({
samples <- colnames(data())
return(samples)
})
如果我使用:samples_names <- c("S1", "S2", "S3", "S4") 并用这个新向量 samples_names 更改 output$selected_sample_one 和 output$selected_sample_two,第二个样本不会改变(见新图片)
但是,如果我增加列数或更改表,则此代码将不起作用。因此,我将其写在反应函数中...
有人知道怎么解决吗?
提前非常感谢
【问题讨论】:
标签: r shiny selectinput