I am trying to create an R Shiny app which can read matrix inputs and extract the anti-diagonal elements, however, I can't figure out why the codes don't work as the way I wanted.
Below are the sample codes:
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)
Below is the sample inputs and outputs:
1st table is the input matrix
2nd table is a 1-row output matrix which shows the sum of each column of the 1st table(not sure if this causes the issue, so I'll just put it there)
3rd table is the output table produced by the codes
Here is the issue, I want the 3rd table to show the anti-diagonal elements 7-5-3 in column A and "reverse anti-diagonal" elements 3-5-7 in column B from the 1st table like below instead of the above (3-3-3- and 7-7-7).
Please help! Thanks!
Solved the issue by changing the codes to below:
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]
}
}