【问题标题】:Creating variable based on reactive one in shiny基于闪亮的反应变量创建变量
【发布时间】:2021-06-04 19:22:50
【问题描述】:

我正在开发一款闪亮的应用程序,它可以计算基本的投资组合统计数据。除了股票,用户还可以定义要分配给特定股票的权重 - 因此具有权重的向量的长度应该等于选择向量的长度,并且总和为 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 函数中做了一些测试输出,所以我可以看看一切是否正常。它还将用户以特定方式(逗号分隔)输入的字符向量转换为数字(我想不出其他方式来做到这一点)。但是,如果用户提供了错误的权重向量(例如当总和不等于 1 或长度不正确时),我需要让应用程序修复权重向量。如果这是反应式的,那将是完美的,因此进一步的计算将自动执行。但是,当我尝试创建包含修复错误的 if 语句的变量时:

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))))})

我收到一个错误:

警告:总和错误:参数的“类型”(闭包)无效

有什么办法吗?

在尝试@stefan 提出的解决方案后,我有另一个问题,现在我收到消息:

警告:strsplit 中的错误:非字符参数

当我尝试使用 weights1() 向量执行计算时。

 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))

代码在使用 weightsx 向量时有效,即为所选投资组合中的每只股票赋予相同的权重。我猜这是从字符到数字的向量转换的问题,但我不知道如何解决这个问题。

【问题讨论】:

  • 只是一个猜测:由于weights 是一个响应式,您必须像函数一样调用它,即尝试在weights1 &lt;- reactive(... 中使用weights() 而不仅仅是weights
  • 帮了大忙,非常感谢!但是我收到另一个错误:strsplit 中的错误:非字符参数;我将编辑原始帖子。

标签: r shiny reactive


【解决方案1】:

正如@stefan 所指出的,可以在末尾添加 () 来访问反应值(就像调用函数一样)。

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))))})

如果名称变量是响应式的,则相同,代码中未指定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2016-12-08
    • 2018-06-05
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多