Aggregate function creates unwanted vector within data frame
I've been experiencing a strange problem with creating dataframes within a
function. However, using the same method outside of a data.frame works
fine!
Here is the basic function, I use it to calculate the mean, standard
deviation and standard error for a data set:
aggregateX<- function(formula, dataset){
output<-aggregate(formula, dataset, mean) #calculate mean
sdev<-aggregate(formula, dataset, sd) #calculate sd
output$sd<-sdev[length(sdev)] #place sd in same data.frame
output$se<-output$sd/sqrt(max(as.numeric(dataset$P))) #calculate se
names(output$sd)<-"sd";names(output$se)<-"se" #attatch correct names
return(output)
}
The function works but has a strange method of combining the data.frame as
an output. The first variable (mean) is formatted correctly, but both the
standard deviation and standard error are structured as a vector within
the dataframes first row.
i.e. when you view the output in RStudio it looks something like this
http://imgur.com/C7IaGG6
This wouldn't matter, but ggplot2 runs into some dificulty when trying to
process this unusual data.frame. Any advice on how to form the data.frame
without the strange vector would be much appreciated.
Many thanks.
No comments:
Post a Comment