在R闪亮中使用时,mean函数返回NaN

时间:2018-01-16 01:14:13

标签: r shiny nan mean

我试图建立一个闪亮的应用程序,我以前从未这样做过。

用户将以这种格式将数据上传到应用程序:

Date        Time1            Time2
01/02/2018  01/02/2018 01:02 01/02/2018 01:04
01/02/2018  01/02/2018 02:03 01/02/2018 02:06
01/02/2018  01/02/2018 03:04 01/02/2018 03:08
01/03/2018  01/02/2018 01:05 01/02/2018 01:10
01/03/2018  01/02/2018 02:06 01/02/2018 02:12
01/03/2018  01/02/2018 03:07 01/02/2018 03:14

我希望应用程序只选择日期范围内的最早日期,并计算两个时间间隔之间的平均分钟数(在我的示例中为3分钟)。输出将如下所示:

Average Time (in minutes):
3

这是我的代码:

shinyUI(pageWithSidebar(
headerPanel("CSV Viewer"),
sidebarPanel(
fileInput('file1', 'Choose CSV File',
          accept=c('text/csv', 'text/comma-separated-values,text/plain', 
'.csv')),
mainPanel(
 textOutput('text1')
 textOutput('text2')
 )
))

shinyServer(function(input, output, session) {

 filedata <- reactive({
 infile <- input$file1
 if (is.null(infile)) {
  return(NULL)
 }
 namedDF <- fread(infile$datapath)
 names(namedDF)[c(1:3)] <- c("Date", "Time1", "Time2")
 return(namedDF)
})

 output$text1 <- renderText({
 "Average Time (in minutes): "
 })

 output$text2 <- renderText({
  myDF <- filedata() # read the uploaded data from reactive
  myDF$Date <- as.Date(myDF$Date, format="%m/%d/%Y") 
  sortedByDate = myDF[order(myDF$Date)]
  day1 = as.Date(sortedByDate$Date, format="%m/%d/%Y")[1]
  namedDF <- sortedByDate[sortedByDate$Date == day1,]
  #convert tender, pickup, depart, arrival and delivery to time objects
  timesData = namedDF[,c(2:3)]
  timesData$Time1 = as.POSIXct(timesData$Time1, format="%m/%d/%Y %H:%M", 
   tz="GMT")
  timesData$Time2 = as.POSIXct(timesData$Time2, format="%m/%d/%Y %H:%M", 
   tz="GMT")
  #compute length of interval, add to original data frame
  interval = 
   as.numeric(difftime(timesData$Time2,timesData$Time1,units="mins"))
  newDF = cbind(namedDF,interval)
  names(newDF)[4]<-c("Delivery.Mins")
  #remove cases with missing records
  newDF_n = na.omit(newDF)
  #clean data
  newDF_n[,4][newDF_n[,13] < 0] <- NA
  newDF_n[,4][newDF_n[,13] > 999] <- NA
  #remove cases with bad data
  newDF_o=na.omit(newDF_n)
  averageTime = mean(newDF_o$Delivery.Mins, na.rm = TRUE)
  averageTime
})

当我运行它时,它返回NaN而不是数字3.我做错了什么?

0 个答案:

没有答案