[R] hist returning density larger than 1

Steven Matthew Anderson adastra69 at mac.com
Thu Jun 4 17:23:51 CEST 2009


The following code is giving me problems.  I want to export densities  
of a distribution to a csv file.  At the bottom of the code I use the  
hist function to generate the densities.  But hist is returning values  
greater than 1.  I don't understand, why.  Any help you can supply is  
greatly appreciated.

# Set word path
dir<-"~/Research/MR Distribution Analysis/"
setwd(dir)
getwd()

# Define Objects
Max.Shots=3
Max.Groups=5000
hist.brks <- pretty(range(c(0,4)), 200)

for(sim in (2:Max.Shots)){
   x.Data<-matrix(nrow=Max.Groups,ncol=sim,byrow=TRUE)
   y.Data<-matrix(nrow=Max.Groups,ncol=sim,byrow=TRUE)
   shot2mean.x<-matrix(nrow=Max.Groups,ncol=sim,byrow=TRUE)
   shot2mean.y<-matrix(nrow=Max.Groups,ncol=sim,byrow=TRUE)
   Euclid.Dist<-matrix(nrow=Max.Groups,ncol=sim,byrow=TRUE)
   mean.radius<-vector(mode="numeric",length=Max.Groups)
   # Generate the Simulation Data
   ###################################################################
   # Number of Groups
   for(Groups in (1:Max.Groups)) {
     # Number of Shots per Group
     for(Shots in (1:sim)) {
       # Populate the Simulation Data
       x.Data[Groups,Shots]<-rnorm(n=1,mean=0,sd=1)
       y.Data[Groups,Shots]<-rnorm(n=1,mean=0,sd=1)
     }
   }
   # Calculate the Component Distances from the Shots to the Group Mean
   # Calculate the Euclidean Distance from the Shots to the Group Mean
   # Calculate the Group Mean Radius
   ###################################################################
   # Number of Groups
   for(Groups in (1:Max.Groups)){
     # Number of Shots per Group
     for(Shots in (1:sim)){
       shot2mean.x[Groups,Shots]<-(x.Data[Groups,Shots]- 
mean(x.Data[Groups,]))^2
       shot2mean.y[Groups,Shots]<-(y.Data[Groups,Shots]- 
mean(y.Data[Groups,]))^2
   	  Euclid.Dist[Groups,Shots]<-sqrt(shot2mean.x[Groups,Shots] 
+shot2mean.y[Groups,Shots])
     }
     mean.radius[Groups]<-mean(Euclid.Dist[Groups,])
   }

   f<-hist(mean.radius,breaks=hist.brks,plot=FALSE)
   density.data<-cbind(sim,f$mids,f$density)
   colnames(density.data)<-c("Simulation","MidPoint","Density")
   if (sim==2) {Simulation.Data<-density.data} else {Simulation.Data<- 
rbind(Simulation.Data,density.data)}

   rm(x.Data)
   rm(y.Data)
   rm(shot2mean.x)
   rm(shot2mean.y)
   rm(Euclid.Dist)
   rm(mean.radius)

}

write.table(
   Simulation.Data,
   file=paste(dir,"/DATA/Simulation_Data.csv",sep=''),
   sep=",",
   quote=FALSE,
   row.names=FALSE,
   qmethod="double")



Steven Matthew Anderson

Anderson Research, LLC
Statistical Programming and Analysis
SAS (R) Certified Professional
AdAstra69 at mac.com

Ad Astra per Aspera

שָׁלוֹם




More information about the R-help mailing list