【问题标题】:R: index entries in ‘order.by’ are not unique (Zoo)R:“order.by”中的索引条目不是唯一的(动物园)
【发布时间】:2019-11-10 20:54:16
【问题描述】:

我正在提取财务数据并尝试以闪亮的方式输出它。我不熟悉动物园功能。为了尝试将正回报设为绿色,将负回报设为红色,我收到以下错误:

动物园警告(cd, order.by = index(x), ...): 如果“order.by”中的索引条目不是唯一的,则“zoo”对象的某些方法不起作用

library(tidyverse)
library(tidyquant)
library(shiny)

#Stock assignments
stock_1<-'AMZN'
stock_2<-'CMG'
stock_3<-'TSS'  
stock_4<-'FB'
stock_5<-'T'

#Creating Input Boxes for Stocks and Weights of the Portfolio
ui <- fluidPage(
  titlePanel('Portfolio Daily Returns'),
  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(6,textInput("S1",h3('Input Stock 1'),stock_1)),
        column(6,numericInput("w1",h3("Input Weight 1"),.25))
      ),
      fluidRow(
        column(6,textInput("S2",h3('Input Stock 2'),stock_2)),
        column(6,numericInput("w2",h3("Input Weight 2"),.25))
      ),
      fluidRow(
        column(6,textInput("S3",h3('Input Stock 3'),stock_3)),
        column(6,numericInput("w3",h3("Input Weight 3"),.2))
      ),
      fluidRow(
        column(6,textInput("S4",h3('Input Stock 4'),stock_4)),
        column(6,numericInput("w4",h3("Input Weight 4"),.2))
      ),
      fluidRow(
        column(6,textInput("S5",h3('Input Stock 5'),stock_5)),
        column(6,numericInput("w5",h3("Input Weight 5"),.1))
      ),
      dateRangeInput("D",h3("Input Start and End Dates"),
                     '2019-09-01',Sys.Date())
    ),
    mainPanel(plotOutput("plot"))
  )
)

#Shows daily volatility of your portfolio returns. Set for the last month but can adjust
server <- function(input,output){
  dataInput <- reactive({
    dat <- tq_get(c(input$S1,input$S2,input$S3,input$S4,input$S5),from=input$D[1],to=input$D[2])%>%
      group_by(symbol)%>%
      tq_transmute(select=volume,mutate_fun = periodReturn,period='daily',
                   col_rename = 'Daily_Vol')%>%
      tq_portfolio(assets_col=symbol,returns_col = Daily_Vol,weights=c(
        input$w1,input$w2,input$w3,input$w4,input$w5),col_rename = 'Port_Vol')
    dat$sign = ifelse(dat$Port_Vol >= 0, "positive", "negative")
    return(dat)
  })


  output$plot <- renderPlot({
    ggplot(dataInput(),aes(x=date,y=Port_Vol))+geom_col()
      scale_fill_manual(values = c("positive"="green","negative"="red"))
  })
}

shinyApp(ui=ui,server=server)

【问题讨论】:

  • 澄清一下,问题出在最后两段代码中。

标签: r ggplot2 shiny zoo


【解决方案1】:

这是获得带有红色和绿色条形图的解决方案。首先更改 dat$sign 赋值语句以匹配以下内容:

dat$sign = ifelse(dat$Port_Vol >= 0, TRUE, FALSE)

然后更改 renderPlot 语句以匹配以下内容:

output$plot <- renderPlot({
  dat <- dataInput()
  ggplot(dat,aes(x=date,y=Port_Vol,fill=sign))+geom_col()+
  scale_fill_manual(values = c("red","green"))
})

我在运行代码时没有收到“动物园”错误,所以我无法帮助您解决这个问题。您可能需要确保在您的机器上更新了 zoo 库。

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多