问题描述
我遇到了一行问题(在 Global.R 下面用散列表示)。我目前正在开发与金融相关的 R 闪亮应用程序。其中一个选项卡包含一个 checkBoxgGroupInput
,它列出了我的源文件中除日期之外的所有列,日期是我可以选择包含在下面的 ggplot 中的股票/指数的名称。
source_file 的示例数据集如下所示:
日期 | 索引 1 | 索引 2 | 索引 3 | 索引 4 | 索引 5 |
---|---|---|---|---|---|
2016-01-01 | +5% | -2% | +5% | +10% | +12% |
2016-01-08 | +3% | +13% | -8% | -3% | +10% |
2016-01-15 | +2% | +11% | -3% | +4% | -15% |
在这种情况下,复选框将加载 5 个选项,索引 1 到索引 5。我设想我将能够选择索引 2 和 3,这将生成一个涉及所选 2 个变量的图(索引 2和 3)。但是,我不确定应该如何参考 checkBoxGroupInput
我尝试执行以下操作以引用 checkBoxGroupInput
输出的第一个和最后一个值,但似乎不起作用。
first <- portfolio_selection[1]
last <- portfolio_selection[length(portfolio_selection)]
asset_returns = source_file[[first:last]]
我希望有人能帮助我找出引用值以实现我的情节的正确方法。我在下面附上了我的 App.R 和 Global.R(我从我的原始代码中简化了代码,因为我不想用超过 150 行的代码淹没这个问题,但逻辑仍然可以正常工作)非常感谢!
App.R
# Load packages
library(shiny)
library(shinythemes)
source("./global.R")
# Defining UI
ui <- fluidPage(theme = shinytheme("darkly"),navbarPage(
"Test App",tabPanel("Target Plot",sidebarPanel(
tags$h4("Input:"),checkBoxGroupInput("portfolio_selection","Select Number of Indexes for Portfolio",choices = list()),),#sidebarpanel
mainPanel(
plotOutput(outputId = "target_plot"),#mainPanel
) #tabpanel
) #navbarPage
) #fluidPage
server <- function(input,output,session) {
#to output target_plot for Target plot
output$target_plot <- renderPlot({
plot_emf(portfolio_selection = input$portfolio_selection)
})
# Column names we want to show - all except `Date`
opts <- setdiff(colnames(source_file),"Date")
# Update checkBoxGroupInput with variables in source_file:
updateCheckBoxGroupInput(
session,"portfolio_selection",choices = opts)
}
# Create Shiny Object
shinyApp(ui = ui,server = server)
全局.R
# Load packages
library(tidyverse)
library(ggcorrplot)
library(zoo)
library(xts)
library(testit)
#choose source file to work with
file_name = file.choose()
source_file = read_csv(file_name)
source_file$Date = as.Date(source_file$Date,format = "%Y-%m-%d")
#########################
plot_emf = function(portfolio_selection)
{
first <- portfolio_selection[1]
last <- portfolio_selection[length(portfolio_selection)]
asset_returns = source_file[[first:last]] ###################issue with this line###################
g = ggplot(data = asset_returns),aes(x =Date,y=asset_returns)) +
ggtitle("Efficient Market Frontier") +
geom_point()
print(g)
}
解决方法
尝试将 plot_emf
函数更改为:
plot_emf = function(portfolio_selection)
{
source_file %>%
select(Date,portfolio_selection) %>%
pivot_longer(cols = -Date) %>%
ggplot() + aes(x =Date,y=value,color = name) +
ggtitle("Efficient Market Frontier") +
geom_point()
}