Reputation: 15
I'm trying to calculate the mean of all columns in a data frame but I get the error : argument is not numeric or logical: returning NA. Here's the code I'm using:
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)
})
})
I'm completely lost and I can't figure out the error. please help me. thanks.
Upvotes: 0
Views: 2524
Reputation: 118
You can calculate the mean of each column of a data frame by using 'colMeans(.)' command. It returns a vector whose each element is the mean of each column in your data frame.
Upvotes: 0
Reputation: 14370
Ok so your main problem si that you're trying to take the mean of a data frame, which is not possible using the mean()
function. This code should work (note since you didn't give any example data I made some up - I threw in a date column in there and the function doesn't take the mean of it).
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")])
})
})
Note that I call dataset()
which allows me to reference the data. This should give you your expected output. Note that I also call the colMeans
function on all the columns in the dataset that are not of the type Date
. You should also be able to substitute your dataframe definition for mine. That is, in my code you would just replace 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"))
with your code in your renderTable()
call.
Hope this helps.
EDIT: Per comments below, it turns out you can can define your data in the renderTable
call and reference it in the renderPrint
. The two main problems were the definition of the data in the read.csv()
and the attempt to call mean
on dataframe. The latter problem is fixed by colMeans()
and the former was fixed using code from @Mouna : dataset<-data.frame(read.csv(inFile$datapath, header = FALSE, sep = ";", dec = ","))
Upvotes: 1