Listing All Variables (Column Names) in R Shiny's checkboxGroupInput

Viewed 303

I'm writing an R shiny application. I'm facing much trouble, particularly the checkboxGroupInput function. I'm hoping that I will be able to create a dynamic list that will automatically list down all columns except the first column, source_file$Date of a dataset named source_file, and I'm not entirely sure on it. Would greatly appreciate any help you can provide!

Sample dataset of source_file would look something like this:

Date Index 1 Index 2 Index 3 Index 4 Index 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%

The end goal is that I hope the checkboxGroupInput function will be able to automatically read all columns starting from the second column (ignore Date). In this case, the check box would load up 5 options, Index 1 to Index 5. It should be replicable such that it can load any number of indexes depending on the data specified. I tried hard-coding each individual index in but it's definitely counter-intuitive and so frustrating to do.

tabPanel("Target Volatility Portfolio",
                         sidebarPanel(
                           tags$h3("Find an optimised portfolio to achieve maximum return for a given level of risk/volatility"),
                           tags$h4("Input:"),
                           checkboxGroupInput("portfolio_selection",
                                              "Select Number of Indexes for Portfolio",
                                              choices = list(#####please send help here#####)

Edits: Would appreciate if you could help me fix this.

I want to reference the output that comes from the checkbox into my global.R in this format. Basically, I want to use the selected variables to plot a graph. A selection of 2 variables will result in a graph plotting a graph related to the 2 variables, whereas a selection of 10 variables will create a plot involving all 10 variables. (I'm basically plotting the efficient market frontier of x number of stocks where x is the number of variables selected. Its a little hard to explain but I hope attaching the code can provide you some insight) The hashed line is what I need help fixing. Thank you!

plot_emf = function(n_points, target_vol, portfolio_selection)
{
  first <- portfolio_selection[1]
  last <- portfolio_selection[length(portfolio_selection)]
  
  #######asset_returns = source_file[first:last]########

  # Extract necessary parameters
  n_assets = ncol(asset_returns)
  n_obs = nrow(asset_returns)
  n_years = n_obs / 52
  
  # Initialize containers for holding return and vol simulations
  return_vector = c()
  vol_vector = c()
  sharpe_vector = c()
  
  for (i in 1:n_points)
  {
  # Generate random weights for n assets from uniform(0,1)
  asset_weights = runif(n_assets, min = 0, max = 1)
  normalization_ratio = sum(asset_weights)
  # Asset weights need to add up to 100%
   
  asset_weights = asset_weights / normalization_ratio
  # print(asset_weights)
  # print(asset_returns)
  
  # Generate the portfolio return vector using these weights
  random_portfolio_returns = emf_portfolio_returns(
    asset_weights,
    asset_returns)
  # print(random_portfolio_returns)
  # plot_returns_histogram(random_portfolio_returns$portfolio_returns)
  
  cumulative_return = calculate_cumulative_return(random_portfolio_returns$portfolio_returns)
  annualized_return = 100*((1 + cumulative_return/100)^(1/n_years) - 1)
  annualized_vol = sd(random_portfolio_returns$portfolio_returns)*(52^0.5)
  sharpe = annualized_return / annualized_vol
  
  return_vector = append(return_vector, annualized_return)
  vol_vector = append(vol_vector, annualized_vol)
  sharpe_vector = append(sharpe_vector, sharpe)
  
  #print(paste("Asset weights:",asset_weights))
  #print(paste("Anualized return:",annualized_return))
  #print(paste("Annualized vol:",annualized_vol))
  }
  
  g = ggplot(data = data.frame(vol_vector, return_vector, sharpe_vector),
             aes(x = vol_vector, y = return_vector, color = sharpe_vector)) +
    scale_color_gradient(low = "red", high = "blue", name = "Sharpe Ratio\n(Return/Risk)") + 
    ggtitle("Efficient Market Frontier") +
    xlab("Annualized Vol (%)") +
    ylab("Annualized Return (%)") + 
    theme(plot.title = element_text(hjust=0.5)) + geom_vline(xintercept=target_vol) +
    geom_point()
  print(g) 
} 
1 Answers

You can try something like the following which uses colnames() to extract the new choices, and then updates the checkboxGroupInput with updateCheckboxGroupInput():

server <- function(input, output, session) {
  
  # Read the data once per session - this step might be better to
  # put in a `global.R` file
  source_file <- read.csv("source_file.csv")
  
  # Column names we want to show - all except `Date`
  opts <- setdiff(colnames(source_file), "Date") 
 
  # Update your checkboxGroupInput:
  updateCheckboxGroupInput(
    session, "portfolio_selection", choices = opts
  )
   
  # Rest of app after this point  --------------------------------------

}
Related