R闪亮-使用for循环提取矩阵中的对角线元素

问题描述 投票:0回答:1

我正在尝试创建一个R Shiny应用程序,该应用程序可以读取矩阵输入并提取反对角线元素,但是,我无法弄清楚为什么这些代码无法按我想要的方式工作。

下面是示例代码:

library(shinyMatrix)
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(shinyjs)
library(rhandsontable)
library(matrixStats)

ui =
  dashboardPage(
    dashboardHeader(disable = TRUE),
    dashboardSidebar(disable = TRUE),
    dashboardBody(rHandsontableOutput("input1"),
                  br(),
                  rHandsontableOutput("input2"),
                  br(),
                  rHandsontableOutput("results")))


server = function (input, output, session) {

  output$input1 = renderRHandsontable({

    MAT = matrix(as.numeric(''), nrow = 3, ncol = 3,
                 dimnames = list(paste(1:3), paste(1:3)))

    rhandsontable(MAT, width = "100%", height = "100%") %>%
      hot_col(col = c(1:3), valign = 'htCenter', format = "0,0")


  })

  row_input <- reactive({
    req(input$input1)

    my_input_matrix <- as.matrix(hot_to_r(input$input1))
    my_input_row<- as.matrix(hot_to_r(input$input1))

    for(i in 1:3) {

      my_input_row[i] = sum(my_input_matrix[,i])


    }


    row_input = matrix(my_input_row, nrow = 1, ncol = 3,
                        dimnames = list("Rowname", paste(1:3)))
    row_input
  })




  output$input2 <- renderRHandsontable({

    rhandsontable(row_input())

  })


table <- reactive({ 

  my_input_matrix <- as.data.frame(hot_to_r(input$input1))
  my_input_row <- as.data.frame(hot_to_r(input$input2))
  my_table <- as.data.frame(hot_to_r(input$input1),
                            hot_to_r(input$input2))


  for(i in 1:3) {
    for(j in 3:1) {

      my_table[,1] <- my_input_matrix[j,i] 
      my_table[,2] <- my_input_matrix[i,j]

    }
  }


  table = data.frame("A" = my_table[,1],
                     "B" = my_table[,2],
                     stringsAsFactors = FALSE,
                     check.names = FALSE)



  table
})

output$results = renderRHandsontable({

  rhandsontable(table()) 

})

}

shinyApp(ui, server)

下面是示例输入和输出:

第一个表是输入矩阵

第二个表是一个1行输出矩阵,它显示了第一个表的每一列的总和(不确定这是否会引起问题,所以我就把它放在这里)

第三表是由代码生成的输出表

enter image description here

[这里是问题,我希望第三张表从第一张表中显示A列中的反对角元素7-5-3和B列中的“反向反对角”元素3-5-7,如下所示(3-3-3-和7-7-7)中的一个。

enter image description here

请帮助!谢谢!

for-loop matrix shiny diagonal
1个回答
0
投票

通过将代码更改为以下解决了该问题:

for(i in 1:3) {
    for(j in 3:1) {

      my_table[,1] <- rev(my_input_matrix[i+(j-1)*3])[i] 
      my_table[,2] <- my_input_matrix[i+(j-1)*3][i]

    }
  }

© www.soinside.com 2019 - 2024. All rights reserved.