2016-08-11 4 views
1

나는 dygraphs와 반짝 이는 사용하려고합니다. 나는 입력 변수에 따라 시계열 데이터를 보여주는 그래프를 생성하려고한다. (제품 A, B 또는 둘 모두를 볼 수) 체크 박스 제품 변수에 대한 제어와반짝 이는 패키지와 함께

 date  product sold 
1 2015-01-01  a 1 
2 2015-01-01  b 20 
3 2015-02-01  a 2 
4 2015-02-01  b 15 
5 2015-03-01  a 3 
6 2015-03-01  b 10 
7 2015-04-01  a 4 
8 2015-04-01  b 5 
9 2015-05-01  a 5 
10 2015-05-01  b 1 

는 내가 원하는 것은 시계열 그래프 : 데이터의 샘플은 다음과 같다.

library(shiny) 
library(dygraphs) 
library(dplyr) 
library(xts) 


ui <- dashboardPage(
skin="black", 
dashboardHeader(title = "title"), 
dashboardSidebar(
    sidebarMenu(
    menuItem("Results", tabName = "Result1", icon = icon("th")) 
)), 
dashboardBody(
    tabItems(

    tabItem(tabName = "Result1", 
      fluidRow(
       dygraphOutput("Graph") 
      ), 

      sidebarPanel(
       uiOutput("output1") 
      ) 

    ) 

)) 
) 

server <- function(input, output) { 


output$Graph <- renderDygraph({ 

    data_f <- filter(data_products, 
       product==input$type) 
    xts(data_f$sold, as.Date(data_f$date, format = "%Y-%m-%d")) %>% 
    dygraph() 
    }) 
    output$output1<-renderUI({ 
    selectizeInput("type","Choose product", 
    choices=levels(data_products$product), multiple=TRUE) 
    }) 
    } 

    shinyApp(ui, server) 

여러 방법을 시도했지만 항상 오류를 얻을 :

는 UI 및 서버 코드 (shinydashboard 패키지)이다. 어떤 조언을 주셔서 미리 감사드립니다.

+0

당신이 생각하기에 가장 좋은 접근 방법이며 어떤 오류가 있으시면 알려주십시오. –

답변

0

당신은 코드의이 부분에서 조심해야 :

data_f <- filter(data_products, 
       product==input$type) 

이 예제에서, 당신의 선택에 따라 input$type 0, 1 또는 2 요소를 포함 할 수 있습니다. 하나의 요소가 "a" 또는 "b" 인 경우 모든 항목이 정상이지만 다른 경우에는 오류 또는 경고가 표시됩니다.

위젯에서 값을 선택하지 않은 경우 input$typeNULL을 반환합니다. 따라서 논리 비교가 실패하고 오류가 발생합니다. 이를 피하기 위해 누락 된 입력을 사용하기 전에 req 또는 validate 기능을 사용할 수 있습니다.이 기능은 "입력이 필요함"으로 읽을 수 있습니다. Here 누락 된 입력을 반짝이는 처리에 대해 자세히 읽을 수 있습니다.

당신은 == 여러 comparisions 작동하지 않기 때문에 모두 "a""b" product==input$type 경고를 반환 할 것입니다 선택한 경우. 이 대신에 %in%으로 변경하십시오.

당신은 내가 checkboxGroupInput


전체 예에 selectInput을 변경 체크 박스 원하기 때문에 :

library(shiny) 
library(dygraphs) 
library(dplyr) 
library(xts) 

# I pasted your example data to exces and then readed it into R with these 
# two lines of the code. It seems that product has to be a factor, because you 
# use 'levels(data_products$product)' 
# data_products <- as.data.frame(read_excel("~/Downloads/data.xlsx"))[-1] 
# data_products$product <- as.factor(data_products$product) 


ui <- dashboardPage(
    skin="black", 
    dashboardHeader(title = "title"), 
    dashboardSidebar(
    sidebarMenu(
     menuItem("Results", tabName = "Result1", icon = icon("th")) 
    )), 
    dashboardBody(
    tabItems(

     tabItem(tabName = "Result1", 
       fluidRow(
       dygraphOutput("Graph") 
      ), 

       sidebarPanel(
       uiOutput("output1") 
      ) 
    ) 
    ) 
) 
) 

server <- function(input, output) { 

    output$Graph <- renderDygraph({ 
    req(input$type) # require that input$type is available 

    data_f <- filter(data_products, 
        product %in% input$type) # use "%in%" instead of "==" 
    xts(data_f$sold, as.Date(data_f$date, format = "%Y-%m-%d")) %>% 
     dygraph() 
    }) 
    output$output1 <- renderUI({ 
    # selectizeInput("type","Choose product", 
    #    choices=levels(data_products$product), multiple=TRUE) 
    checkboxGroupInput("type", "Choose product", 
         choices = levels(data_products$product), 
         selected = levels(data_products$product)) 
    }) 
} 

shinyApp(ui, server) 

편집을 :

ab이 선택되었을 때 두 줄을 원한다면, 데이터의 형식을 변경해야합니다. 길고 길게 가야합니다. 그 이유는 xtsdygraph으로 이변 변수 시계열을 쉽게 만들 수 있기 때문에 두 개의 별도 라인을 그릴 수 있기 때문입니다.

해들리 위크 햄 (Hadley Wickham)의 reshape2 패키지를 사용하여 길게에서 와이드로 쉽게 이동할 수 있습니다.

# Copy data from your example 
data_products <- read.table(con<-file("clipboard"),header=T) 
data_products$product <- as.factor(data_products$product) 
# Reshape 
data_products <- dcast(data_products, date ~ product) 

데이터 집합은 다음과 같이 지금 같습니다

 date a b 
1 2015-01-01 1 20 
2 2015-02-01 2 15 
3 2015-03-01 3 10 
4 2015-04-01 4 5 
5 2015-05-01 5 1 

인해 데이터의 새로운 특성이 약간 서버 측에서 코드를 변경해야합니다.코드에 주석을 남겼습니다.

ui <- dashboardPage(
    skin = "black", 
    dashboardHeader(title = "title"), 
    dashboardSidebar(
    sidebarMenu(
     menuItem("Results", tabName = "Result1", icon = icon("th")) 
    )), 
    dashboardBody(
    tabItems(

     tabItem(tabName = "Result1", 
       fluidRow(
       dygraphOutput("Graph") 
      ), 

       sidebarPanel(
       uiOutput("output1") 
      ) 
    ) 
    ) 
) 
) 

server <- function(input, output) { 

    output$Graph <- renderDygraph({ 
    req(input$type) # require that input$type is available 

    # Due to the wide format we have to select columns 
    data_f <- data_products[, c("date", input$type)] 
    # univariate or bivariate time series 
    xts(data_f[-1], as.Date(data_f$date, format = "%Y-%m-%d")) %>% 
     dygraph() 
    }) 

    output$output1 <- renderUI({ 
    # Since we now have data in wide format, the choices are 
    # the names of columns (expect date) 
    checkboxGroupInput("type", "Choose product", 
         choices = names(data_products)[-1]) 
    }) 
} 

shinyApp(ui, server) 
+0

감사합니다. 작동합니다! 한 가지 더. 체크 상자에 "a"와 "b"를 모두 선택하면 한 줄만 나타나고 두 개가 아닌 ... 나는 초보자 용 질문이지만 R과 Shiny를 처음 사용한다는 것을 알고 있습니다. 감사. – TomasD

+0

위의 게시물을 업데이트했습니다. 데이터 형식을 변경해야하기 때문에 솔루션이 매우 쉽다는 것을 알게되었습니다. –

+1

도움을 주셔서 대단히 감사합니다 !!! – TomasD

관련 문제