闪亮 - 如何从存储在被动函数中的数据框中选择列

时间:2014-07-11 22:01:32

标签: r shiny

我差不多用Shiny创建了我的第一个网络应用程序,但是我在最后一步停留,我正在渲染情节。 我要做的是根据ui.R的输入,在我的renderPlot()函数中反应性地选择y轴。

要详细说明问题,我的server.R如下所示:

library(shiny)
library(plyr)
library(sqldf)
library(reshape2)
library(ggplot2)
suppressWarnings(library(RODBC))



user=c(260, 2670, 3209, 7992, 8176, 10001, 10254, 11576, 17801, 17801)
var1=c(3, 2, 42, 1, 6, 4, 2, 9, 1, 4)
var2=c(65, -3680, -2457, 5200, -100, 1000, -50, 630, -124, 439)
date=c("2014-07-01", "2014-07-02", "2014-07-03", "2014-07-04", "2014-07-05", "2014-07-05", "2014-07-05", "2014-07-06", "2014-07-07", "2014-07-08")
id=c(41, 48, 41, 48, 50, 41, 48, 41, 41, 50)

data2mutate<-data.frame(user, var1, var2, date = as.Date(date), id)


#The Shiny Server starts here:

shinyServer(
  function(input, output) {
dataInput<-reactive({

  mutate(
    merge(
#First data frame in the merge function
      setNames(count(data2mutate, c('date', 'id')), c('date', 'id', 'number_users'))
#Second data frame in the merge function
      , setNames(aggregate(cbind(var1, var2) ~ date+id, data2mutate , sum), c('date', 'id', 'var1','var2'))
#By:
      , by=c('date', 'id'), all.x=T),
#Variables created with the mutate function
    var3=round(var1/number_users, 1), var4=round(var2/number_users, 1))[,c(1,3,4,6,5,7,2)] #At the end I reorder the columns so that their place will match the input number from ui.R

})

# Create the plot
output$plot1<- renderPlot({
                print(ggplot(dataInput() , aes(x=as.Date(date), y=number_users)) + 
                geom_line() + 
                labs(x = "Date", y="Number of Users")
  )

    }
)        

所以,在server.R中,如果我为x轴分配给定变量,一切正常:

output$plot1<- renderPlot({
                print(ggplot(dataInput() , aes(x=as.Date(date), y=number_users)) + 
                geom_line() + 
                labs(x = "Date", y="Number of Users")
  )

尽管如此,我想根据ui.R(名为selectKPI )的输入从dataInput()中反应性地选择y轴。我最好的猜测就是这个:

output$plot1<- renderPlot({
                print(ggplot(dataInput() , aes(x=as.Date(date_played), y=dataInput()[input$selectKPI[1]]))) + 
                geom_line() + 
                labs(x = "Date", y=as.symbol(names(dataInput())[input$selectKPI[1]]))
  )

我可以通过对每个ui.R输入使用if语句来解决这个问题,但我发现这有点沉闷+我很好奇你是否可以从反应函数中选择一列。

0 个答案:

没有答案