Search code examples
rshinydata-manipulation

adding a column in shiny


I would like to add an ID column to a data set using Shiny. And this ID column can be as long as the dataset dat$my.ID <- (max(dat$ID) + 1):(max(dat$ID) + nrow(dat)) and should not limit the user who is entering a starting ID number. many thanks in advance.

ui.r

 navbarPage(
  title = 'Benvenuti',
  tabPanel('read.me', column(3,
                             
                             h3("Daily Data Manipulation"),
                          
                             h3("title1"),
                             tags$a("Upload data.xlsx")
  )),
  
  tabPanel(title = "title2", 
           sidebarPanel( width = 2, fileInput('file1', 'Choose xlsx file',
                                              accept = c(".xlsx")),
                         numericInput("ID", "enter the id number to increment", THERE SHOULD BE NO LIMIT IN MIN AND MAX )
           ), 
           
           mainPanel(tableOutput(outputId = "mytable"))
  ) ) 

server.r

library(shiny)

server <- function(input, output) {
  
  ########################################
  ### title1
  ########################################  
  
  data.Consenso <- reactive({
    inFile <- input$file1
    if(!is.null(inFile)) {
      readxl::read_excel(inFile$datapath)
      #read.csv(inFile$datapath, header = TRUE, stringsAsFactors = FALSE)    
    }
  })
  
  
  output$mytable <- renderTable({
    
    dat <- data.Consenso()
    if(!is.null(dat))
    {
      dat$Tipo <- 3
      dat$my.ID <- (max(dat$ID) + 1):(max(dat$ID) + nrow(dat)) 
      dat
    }
  }) 
  
  
  
}

Solution

  • This should work:

    Made changes in ui: tabPanel(title = "title2",... and in server: starting_id <- input$ID takes the input from the user and makes a sequence of IDs starting from the user input and incrementing by 1.

    ui.r

    library(shiny)
    
    navbarPage(
      title = 'Benvenuti',
      tabPanel('read.me', column(
        3,
        
        h3("Daily Data Manipulation"),
        
        h3("title1"),
        tags$a("Upload data.xlsx")
      )),
      
      tabPanel(
        title = "title2",
        sidebarPanel(
          width = 2,
          fileInput('file1', 'Choose xlsx file', accept = c(".xlsx")),
          numericInput(
            "ID",
            "Enter the starting ID number:",
            value = 1,
            min = -Inf,
            max = Inf
          )
        ),
        mainPanel(tableOutput(outputId = "mytable"))
      )
    ) 
    

    server.r

    server <- function(input, output) {
      data.Consenso <- reactive({
        inFile <- input$file1
        if (!is.null(inFile)) {
          readxl::read_excel(inFile$datapath)
        }
      })
      
      output$mytable <- renderTable({
        dat <- data.Consenso()
        if (!is.null(dat)) {
          dat$Tipo <- 3
          starting_id <- input$ID
          dat$my.ID <- starting_id:(starting_id + nrow(dat) - 1)
          dat
        }
      })
    }