【问题标题】:In R, is it possible to use a dynamic formula for matrix row and column indices?在 R 中,是否可以对矩阵行和列索引使用动态公式?
【发布时间】:2021-12-03 12:56:54
【问题描述】:

下面的代码部分可以很好地从垂直扩展的矩阵中提取值,一次到达一个添加的行(请特别注意我在 # << 代码中的注释):

plotData <- reactive({
    req(dim(sanitizedMat())[1] >= 1)
    lapply(seq_len(nrow(sanitizedMat())),
           function(i){
             tibble(
               Scenario = rownames(sanitizedMat())[i],
               X = 1:input$periods,
               Y = interpol(input$periods, sanitizedMat()[i, 1:2]) # << note the matrix index [i,1:2]
             )
           }) %>% bind_rows()
  })

但是,在我尝试将矩阵读数重新定向为 2 数据对中的水平方向时,我想对矩阵索引进行更改,如下所示,其中 interpol() 函数应用于 Y(强调注意 @ 987654324@):

plotData <- reactive({
    req(dim(sanitizedMat())[1] >= 1)
    lapply(seq_len(ncol(sanitizedMat()))/2,
           function(i){
             tibble(
               Scenario = rownames(sanitizedMat())[i],
               X = 1:input$periods,
               Y = interpol(input$periods, sanitizedMat()[1, i*2-1:i*2]) # << note attempt to use formula for matrix index
             )
           }) %>% bind_cols()
  })

是否可以使用矩阵索引公式,就像我在上面尝试的[1, i*2-1:i*2] 一样?如果可能的话,我很确定我的语法是错误的,但这说明了这个想法。

这将允许我水平跳过矩阵,在 2 列之间跳跃,因为 lapply 通过 i 迭代。

【问题讨论】:

  • 最终[1, (i*2-1):(i*2)]

标签: r matrix shiny lapply


【解决方案1】:

参考帖子How to automatically delete a matrix column in R if there otherwise would be subscript out of bounds error?,它反映了动态矩阵索引并提供了完全解析的代码。

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多