在我的下面的脚本中,Shiny从PostgresSQL中获取数据作为反应函数,我想操纵该反应函数的输出(就像我们在数据框中那样),这样我就可以将它传递给renderPlot函数来获得我想要的输出。
如果有任何帮助,我将非常感谢让我知道如何使这项工作。我没有包含错误消息,因为我认为在处理反应函数时发生了错误。
感谢您的帮助!非常感谢。
#server side operation
library(shiny)
library(dplyr)
library(ggplot2)
library(DBI)
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <-dbConnect(drv,dbname = "", host = "valid credentials", port = 5439,
user = "USER", password = "password")
dates <- seq(as.Date(as.character(Sys.Date() - 33)), as.Date(as.character(Sys.Date() - 1)), by = 1)
shinyServer(function(input, output, session) {
generate <- function(dates){
listofdfs <- list() #Create a list in which you intend to save your df's.
for (i in 1:length(dates)){
data <- reactive({dbGetQuery(con, sprintf("select Column A, CAST (date AS date), id from My_Table
where id =", input$user_id," and
date <= '%s' and date >= '%s'- INTERVAL '7 days'", dates[i], dates[i]))
data$Column_A_mean <- mean(data[,1]) #creating a new column like we do in a data frame (DF)
})
listofdfs[[i]] <- data() # save your dataframes into the list
}
return(listofdfs) #Return the list of dataframes.
}
df <- do.call("rbind", generate(dates))
output$Coolplot <- renderPlot({
ggplot(data = df, aes(date)) +
geom_line(aes(y = Column A, colour = "Column A"))+
geom_line(aes(y = Column_A_mean, colour = "Column_A_mean"))
})
})
答案 0 :(得分:1)
你必须将reactive
放在函数之外,例如你可以从reactive
调用函数:
shinyServer(function(input, output, session) {
generate <- function(dates){
listofdfs <- list() #Create a list in which you intend to save your df's.
for (i in 1:length(dates)){
data <- dbGetQuery(con, sprintf("select Column A, CAST (date AS date), id from My_Table
where id =", input$user_id," and
date <= '%s' and date >= '%s'- INTERVAL '7 days'", dates[i], dates[i]))
data$Column_A_mean <- mean(data[,1]) #creating a new column like we do in a data frame (DF)
listofdfs[[i]] <- data() # save your dataframes into the list
}
return(listofdfs) #Return the list of dataframes.
}
df <- reactive({do.call("rbind", generate(dates))})
output$Coolplot <- renderPlot({
ggplot(data = df(), aes(date)) +
geom_line(aes(y = Column A, colour = "Column A"))+
geom_line(aes(y = Column_A_mean, colour = "Column_A_mean"))
})
})