简体   繁体   中英

How to implement following R function?

I am trying to create a function to do the following in R:

Input parameters n , s , x-bar all integers.

  1. Generate n - 1 random numbers using rnorm( n - 1 , 0 , 1) .
  2. Take each of the numbers, square it, and add them up and store the sum into x . Divide integer s by x and take square root of the result and store into sigma
  3. Generate a single value from N(0,1). rnorm( 1 , 0 , 1) and store into Z .
  4. Then store into mu the value of Z x ( sigma / sqrt(n) ) + x-bar .
  5. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM