The answer to this question will help me answer a question I posted earlier today.
In order to run some calculations from an input matrix, I need to be able to extract dimension names and list those names in a separate vector.
Below MWE code runs an example, using package R shiny. Doesn't matter if you input into the matrix or not as 2 default values are randomly generated in any case. I have a section of code (at oe1 <-
near the bottom) that extracts the matrix values: after running the App, type "samples.R" in the R Studio console and see output of matrix values. I need to be able to extract the matrix column names and place them in a separate vector (for calculations that will be used in the fuller App this MWE derives from). As shown and explained in the image at the bottom, a snapshot of examining the matrix values in the R Studio console. How can this be done?
MWE code:
library(shiny)
library(shinyMatrix)
m <- matrix(runif(2), 1, 2, dimnames = list(c("Values"), c(1:2)))
ui <- fluidPage(
titlePanel("Matrix inputs"),
sidebarPanel(
width = 6,
matrixInput(
"sample",
value = m,
rows = list(extend = FALSE),
cols = list(extend = TRUE, names = TRUE, editableNames = TRUE, delete = TRUE),
class = "numeric"
)
),
mainPanel(
width = 6,
plotOutput("scatter")
)
)
server <- function(input, output, session) {
output$scatter <- renderPlot({plot(1:ncol(input$sample),input$sample,xlab="Nbr",ylab="Values")})
oe1 <- reactive({req(input$sample) # <<< capture matrix inputs for function development
input$sample})
observeEvent(oe1(),{sample.R <<- oe1()})
}
shinyApp(ui, server)
CodePudding user response:
You may use colnames
to get the column names of the matrix.
observeEvent(oe1(),{
sample.R <<- oe1()
cm1 <<- colnames(oe1())
})
You can check this vector in the console after running the app.
cm1
[1] "1" "2"
If you are using these values in the app you don't need to use <<-
.
CodePudding user response:
We can also do
observeEevent(oe1(), {
tmp <- oe1()
sample.R <- tmp
cm1 <- colnames(tmp)
})