我有一个可能很愚蠢的问题,但我只是想创建我的第一个 R shiny 应用程序。我正在考虑编写一个代码,其中将读取 2 个单独的 csv 文件,然后将其组合成一个数据帧。在组合它们之前,我需要在每个数据框中添加几列,如代码所示。所以我想我可以在 ui 和服务器之外操作数据,然后创建应用程序,允许用户选择他们想要在每个轴上绘制的内容。 Shiny 部分之外的代码的第一部分工作正常,我得到了所需的组合数据框。但是,当我运行代码时,似乎没有创建数据框,因此我最终得到一个空界面。
任何帮助将不胜感激!我附上了其中一个 csv 文件中列的图片,第二个 csv 文件类似。
shop1.csv
library(tidyverse)
library(shiny)
twofiles<-c("shop1.csv","shop2.csv")
shop_list<-lapply(twofiles, read.csv, header=TRUE, sep=",")
shop_list<- lapply(seq_along(shop_list), function(i){
df <- shop_list[[i]]
df<-transform(df,ratio1=price_apples/price_pears)
df<-transform(df,ratio2=price_apples/price_cherries)
df<-transform(df,datano=i)
})
finaldata <- do.call(rbind, shop_list)
finaldata$datano <- factor(finaldata$datano)
ui<-fluidPage(
titlePanel("Shops plots"),
sidebarMenu(
selectInput(inputId = "x", label = "Select x-axis:",
choices = c("Year"="year","Hour"="hour"), selected="year"),
selectInput(inputId = "y", label = "Select y-axis:",
choices = c("Ratio 1"="ratio1","Ratio 2"="ratio2"),selected="ratio1"),
mainPanel(
plotOutput("plot")
)
)
)
server<-function(input, output) {
output$plot <-renderPlot({
ggplot(finaldata, aes(x=input$x, y=input$y, group=datano, color = datano)) +
geom_line()
})
}
shinyApp(ui=ui, server=server)
最佳答案
评论太长了:
以下是使用 mtcars
数据集的示例代码:
您必须在 ggplot
中使用 aes_string
而不是 aes
。
Dataframe 操作(包括加载等)应该在服务器端完成。
还有一件事是 group=datano
和 color=datano
也可能容易出现问题。在此处尝试 yourdataframe$datano
library(shiny)
library(dplyr)
library(ggplot2)
ui<-fluidPage(
titlePanel("XXX"),
sidebarMenu(
selectInput(inputId = "x", label = "Select x-axis:",
choices = c("mpg"="mpg","disp"="disp"), selected="mpg"),
selectInput(inputId = "y", label = "Select y-axis:",
choices = c("hp"="hp","drat"="drat"),selected="hp"),
mainPanel(
plotOutput("plot")
)
)
)
server<-function(input, output,session) {
output$plot <-renderPlot({
ggplot(finaldata, aes_string(x=input$x, y=input$y, group=mtcars$cyl, color = mtcars$cyl)) +
geom_line()
})
}
shinyApp(ui=ui, server=server)
https://stackoverflow.com/questions/70636736/