闪亮计算数据框中列的平均值

Shiny calculate the mean of columns in dataframe

我正在尝试计算数据框中所有列的平均值,但出现错误:参数不是数字或逻辑:返回 NA。 这是我正在使用的代码:

UI.R

library(shiny)
library(shinydashboard)
library(plyr)
library(reshape2)

#library(data.table)

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


  ),
  mainPanel(

    tableOutput('data'),
    verbatimTextOutput('mean')

  )
))

server.UI

shinyServer(function(input, output,session) {

  output$data <- renderTable({
    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    data<-data.frame(read.csv(inFile$datapath, header=FALSE, sep=";"))

  })
  output$mean<-renderPrint({

   mean(data)

  })
})

我完全迷路了,我无法找出错误。请帮我。谢谢。

好的,所以你的主要问题是你试图获取数据框的平均值,而使用 mean() 函数是不可能的。这段代码应该可以工作(请注意,因为你没有提供任何示例数据,所以我做了一些 - 我在其中放入了一个日期列,并且该函数不采用它的平均值)。

shinyServer(function(input, output,session) {

  dataset <- reactive({
    #Change the below line
    data.frame(a=c(1,2,3),b=c(2,4,5),c=as.Date(c("12/31/09","12/31/10","12/31/11"),"%m/%d/%y"))

  })

  output$mean<-renderPrint({

   colMeans(dataset()[,which(sapply(dataset(), class) != "Date")])

  })
})

请注意,我调用了 dataset(),它允许我引用数据。这应该会给你预期的输出。请注意,我还对数据集中所有非 Date 类型的列调用了 colMeans 函数。您还应该能够用您的数据框定义替换我的。也就是说,在我的代码中,您只需将 data.frame(a=c(1,2,3),b=c(2,4,5),c=as.Date(c("12/31/09","12/31/10","12/31/11"),"%m/%d/%y")) 替换为您在 renderTable() 调用中的代码。

希望对您有所帮助。

编辑: 根据下面的评论,事实证明您可以在 renderTable 调用中定义数据并在 renderPrint 中引用它。两个主要问题是 read.csv() 中数据的定义和对数据帧调用 mean 的尝试。后一个问题由 colMeans() 修复,前者使用来自@Mouna 的代码修复:dataset<-data.frame(read.csv(inFile$datapath, header = FALSE, sep = ";", dec = ","))

您可以使用“colMeans(.)”命令计算数据框每一列的平均值。它 returns 一个向量,其每个元素都是数据框中每一列的平均值。