2016-09-22 2 views
0

Как отображать возраст автоматически, когда дата рождения вводится в R блестящий? UI.RКак отображать возраст автоматически, когда дата рождения вводится в R блестящий?

shinyUI(
    fuildpage({ 
    column(2, actionButton("calculate", "Calculate age")), 
    fluidRow(uiOutput("calculatedage") 
}) 

SERVER.R

library(shiny) 
library(shinyjs) 
library(shinythemes) 

shinyServer(function(input, output,session){ 

    observeEvent(input$calculate, 
     output$calculatedage <- renderUI({isolate({ 

     fluidRow(
      column(3,dateInput("dob", label="DATE OF BIRTH:",min = "1960-01-01", 
      max = Sys.Date(), format = "yyyy-mm-dd", startview = "year", 
      weekstart = 0, language = "en")), 

      column(3, textInput("age",label = "AGE:")), 
     column(3,textInput("address",label = "Address:"))            
     ) 

    })}))   
}) 

В приведенном выше коде есть кнопка называется вычислить возраст, когда что щелкнул пользователь может ввести dob.When пользователь вводит в DOB возраст должен отображаться автоматически в текстовом поле, определенном «возраст». Как это можно сделать в R блестящем

ответ

0

Как насчет этого?

library(shiny) 
library(shinyjs) 
library(shinythemes) 

ui <- shinyUI(
    fluidPage({ 
    column(2, actionButton("calculate", "Calculate age"), 
    fluidRow(uiOutput("calculatedage"))) 
    }) 
) 

server <- shinyServer(function(input, output,session){ 

     observeEvent(input$calculate, 
        output$calculatedage <- renderUI({isolate({ 

         fluidRow(
         column(10,dateInput("dob", label="DATE OF BIRTH:", 
              min = "1960-01-01", 
              max = Sys.Date(), format = "yyyy-mm-dd", 
              startview = "year", 
              weekstart = 0, language = "en")), 

         column(10, textInput("age",label = "AGE:")), 
         column(10,textInput("address",label = "Address:"))            
        ) 

        })})) 

     observe({ dob <- input$dob 
        if(!is.null(dob)) { 
        days <- as.integer((Sys.Date() - as.Date(dob))) 
        years <- as.integer(days/365) 
        months <- as.integer((days %% 365)/30) 
        age <- paste(years, 'year(s)', months, 'month(s)')           
        #print(age) 
        updateTextInput(session, "age", value = age) 
        } 

      }) 
}) 

shinyApp(ui = ui, server = server) 

enter image description here

+0

Спасибо Сэра он работал, но может возраст печататься в месяцах и года формат, Ф.О. Пример 3 года 2 месяца. – Anu

+0

обновил код, не могли бы вы отложить ответ? –

+0

Спасибо, сэр, это сработало. Сэр, моя репутация - одна, я проголосовал, но отображается сообщение о том, что голосование от тех, у кого репутация ниже 15, записано, но не меняет общедоступный рейтинг публики. – Anu

0

создание динамичного блестящее приложения, так что когда вы входите предыдущие даты автоматически рассчитать согласно дней, месяцев и года в 3 диффах столбцов, вы можете добавить стольких предыдущих даты, как вы можете ее генерирует выходную таблицу в блестящем приложении

library(shiny) 
library(lubridate) 

ui <- shinyUI(fluidPage(
        titlePanel("Date calculator"), 
        sidebarLayout(
        sidebarPanel(
        textInput("Possible.date", label="Previous date", value= "2016-08-23"), 
        textInput("Current.date", label="Current .date", value=Sys.Date()), 
        actionButton("addButton", "Calculate") 
         ), 
mainPanel(
      tableOutput("table")) 
      ))) 

server = function(input, output) {  


values <- reactiveValues() 
values$df <- data.frame(Possible.date = NA, Current.date = NA, Age_days = NA ,Age_months=NA, Age_years = NA) 



observeEvent(input$addButton, { 

if(input$addButton >= 0) { 
    # create the new line to be added from your inputs 

    newLine <- isolate(c(lubridate::ymd(input$Possible.date), lubridate::ymd(input$Current.date), 
    difftime(lubridate::ymd(input$Current.date),lubridate::ymd(input$Possible.date)), 
    (difftime(lubridate::ymd(input$Current.date),lubridate::ymd(input$Possible.date)))/30, 
    (difftime(lubridate::ymd(input$Current.date),lubridate::ymd(input$Possible.date)))/365)) 
    isolate(values$df <- rbind(as.matrix(values$df), unlist(newLine))) 
    } 
}) 

output$table <- renderTable({values$df}, include.rownames=F) 


    } 

shinyApp(ui = ui, server = server) 

enter image description here

+0

@ Вы можете добавить кнопку загрузки, если вам нужно загрузить файлы в формате .csv –

Смежные вопросы