I am trying to create a function to do the following in R:
Input parameters
n
,s
,x-bar
all integers.
- Generate
n - 1
random numbers usingrnorm( n - 1 , 0 , 1)
.- Take each of the numbers, square it, and add them up and store the sum into
x
. Divide integers
byx
and take square root of the result and store intosigma
- Generate a single value from N(0,1).
rnorm( 1 , 0 , 1)
and store intoZ
.- Then store into
mu
the value ofZ x ( sigma / sqrt(n) ) + x-bar
.- Print out
mu
.
Any help would be appreciated !
My attempt( Is this right ?)
g <- function( n , s , xb ) {
vals <- rnorm( n - 1 , 0 , 1)
sum <- 0
for( i in vals )
{
sum <- sum + (i * i )
print( sum )
}
sigma <- sqrt ( s / sum )
z <- rnorm(1, 0 , 1)
mu <- ( z * ( sigma / sqrt(n) ) + xb )
print ( mu)
}
g <- function( n , s , xb ) {
vals <- rnorm( n - 1 , 0 , 1)
sum<- sum(vals^2)
sigma <- sqrt ( s / sum )
z <- rnorm(1, 0 , 1)
mu <- ( z * ( sigma / sqrt(n) ) + xb )
print ( mu)
}
g(10,6,3)
[1] 2.89561
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.