In this code I want to calculate the trimmed mean and variance of trimmed mean for normal distribution in many value of alpha ( I want to calculate the value of the each alpha from 1 to 13 ) and storage the result in the data.frame then print the all result But the problem is that the new result storages over the previous result and at the end i end up getting only the last result of alpha value.
ProDistFun<- data.frame(matrix(nrow=91, ncol=4))
colnames(ProDistFun)<-c("x","Alpha","Trimmed Mean","Variance Of Trimmed Mean")
mu=7 # Mean Value
sigma2=4 # Variance value
for (alpha in c(0.001,0.01,0.025,0.05,0.1,0.25,0.375))
{
for(i in 1:13)
{
ProDistFun[i,1]<-i
ProDistFun[i,2]<-alpha
# The trimmed mean
a=qnorm(alpha, mean=mu, sd=sqrt(sigma2))
b=qnorm(1-alpha, mean=mu, sd=sqrt(sigma2))
fun_TM <- function(x) ((x*exp(-0.5*((x-mu)/sqrt(sigma2))^2))/((1-2*alpha)*(sqrt(2*pi*sigma2))))
MT1 <- integrate(fun_TM, a, b)
MT <-MT1$value
ProDistFun[i,3]<-MT
# The variance of trimmed mean
fun_VTM <- function(x) ((((x-MT)^2)*exp(-0.5*((x-mu)/sqrt(sigma2))^2))/(sqrt(2*pi*sigma2)))
fVTM <- integrate(fun_VTM, a, b)
fV <- fVTM$value
VT=((fV+(alpha*(a-MT)^2)+(alpha*(b-MT)^2))/((1-2*alpha)^2))
ProDistFun[i,4]<-VT
}
}
print(ProDistFun)
Edited Sept 30 12:23 hours
It's still not totally clear to me what you're trying to accomplish with x since you use it in confusing ways, but using most of your code and simplifying drastically but still using a
for loop
Create an empty dataframe without the matrix contortions.
Assign your two constants. IMPORTANT NOTE -- throughout your code please stop treating assignment
<-
as the same thing as=
it will cause problems down the road.Pull your two functions out of the loops (no point in rerunning them every iteration). I have no idea if they are correct but they seem to work. It also seems to me that in these functions you want the x value to be the value of
i
so I've made that change. If you don't you get 13 iterations of identicalNow we run the nested loops of
alpha
andi
. We build a row to add to our empty dataframeProDist_df
and then last step isrbind
thenewrow
to it. Note as stated in the help file forintegrate
we need toVectorize
.