R 基于项目中的被动变量创建变量

R 基于项目中的被动变量创建变量,r,shiny,reactive,R,Shiny,Reactive,我正在开发Shining应用程序,它可以计算基本的投资组合统计数据。除了股票之外,用户还可以定义要分配给特定股票的权重,因此权重向量的长度应该等于选择向量,总和为1 我在服务器函数中编写了这部分代码,我希望它在单击下载按钮后显示: ui: uiOutput("weights") server: output$weights <- renderUI({ textInput('weights', 'Enter a vector of weights (comma

我正在开发Shining应用程序,它可以计算基本的投资组合统计数据。除了股票之外,用户还可以定义要分配给特定股票的权重,因此权重向量的长度应该等于选择向量,总和为1

我在服务器函数中编写了这部分代码,我希望它在单击下载按钮后显示:

ui:
 uiOutput("weights")

server:
output$weights <- renderUI({
   textInput('weights', 'Enter a vector of weights (comma delimited - sum must be equal to 1)', 
   value=paste(rep(round(1/length(input$choices),digits=2), times=length(input$choices)), 
   collapse=", "))})

weights <- reactive(
           as.numeric(unlist(strsplit(input$weights, ","))))
ui:
输出(“重量”)
服务器:

输出$weights正如@stefan所指出的,可以通过在末尾添加()来访问被动值(如调用函数)


weights 1只是一个猜测:由于
weights
是一个反应式函数,您必须像调用函数一样调用它,即在
weights 1中尝试使用
weights()
,这很有帮助,非常感谢!然而,我得到了另一个错误:strsplit中的错误:非字符参数;我将编辑原始帖子。
weights1 <- reactive({
                (if(length(weights)==length(names) & sum(weights)==1) weights else
                if(length(weights)==length(names) & sum(weights)!=1) c(weights/sum(weights)) else
                  c(rep(1/length(names),length(names))))})
 PortfolioReturn <- function(names, stocks, weights) 
            {
              # portfolio = close_price*weight
              portfolio <- as.data.frame(mapply('*', stocks[,-1], weights))
              #row.names(portfolio) <- stocks$Date
              # daily return = (P(t) - P(t-1)) / P(t-1)
              # it is the percentage price difference
              returns <- as.data.frame(apply(portfolio, 2, diff.xts, lag = 1)/apply(portfolio, 2, DataCombine::shift, shiftBy = -1, reminder = FALSE))
              returns
              # cumulate daily returns
              returns$cum_returns <- as.vector(apply(returns, 1, sum))
              return(returns)
            }
            
            
            ((((
            
            weightsx <- rep(round(1/length(input$choices),digits=2), times=length(input$choices))
            
            returns <- PortfolioReturn(input$choices, stocks, weights1())
            output$returns <- renderTable(tail(returns))
weights1 <- reactive({
    (if(length(weights())==length(names) & sum(weights())==1) weights() else
        if(length(weights())==length(names) & sum(weights())!=1) c(weights()/sum(weights())) else
            c(rep(1/length(names),length(names))))})