JVicM
JVicM

Reputation: 67

Can I copy the result of an output and use it in an R/Shiny function?

I would like to copy the output result "my archive" (upload file name without extension) and use it in a function ( name( ) ) to read the column labels from a spreadsheet. It is possible?

Thanks for the help.

The code:


    library(shiny)
ui <- fluidPage(
    
    fileInput("archive", "upload file", accept = c(
        ".xlsx")),

    textOutput("my_archive"),
    textOutput("top"))


server <- function(input, output) {
    
    
    csv <- reactive({
        inFile <- input$archive
        if (is.null(inFile))
            return(NULL)
        df<- read.xlsx(inFile$datapath, header=T)
        return(df)
    })
    
    output$my_archive <- renderText({
        # Test if file is selected
        if (!is.null(input$x$datapath)) {
            return(sub(".xlsx$", "", basename(input$archive$name)))
        } else {
            return(NULL)
        }
    })
    
    output$top <- 
        renderPrint({
            names("output$my_archive")
        })
    
}


shinyApp(ui, server)

Upvotes: 1

Views: 185

Answers (1)

jpdugo17
jpdugo17

Reputation: 7106

This will read a xlsx file and output the file name without extension and the column names.

library(shiny)
library(tidyverse)
library(readxl)
library(stringr)

ui <- fluidPage(
    fileInput("archive", "upload file", accept = c(
        ".xlsx")),
    
    textOutput("my_archive"),
    textOutput("top"))
)

server <- function(input, output, session) {
    #read the file
    csv <- reactive({
        req(input$archive)
        inFile <- input$archive
        df<- read_xlsx(inFile$datapath)
        print(df)
        return(df)
    })
    
    #name of the file without extension
    output$my_archive <- renderText({
        # Test if file is selected
        if (!is.null(input$archive)) {
            return(str_replace(input$archive$name, '\\.xlsx', ' ') )
        } else {
            return(NULL)
        }
    })
    
    #column names
    output$top <- 
        renderText({
            names(csv())
        })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions