Robert_V._Hogg,_Joseph_W._McKean,_Allen_T._Craig

(Jacob Rumans) #1
B.4. Loops 699

hence, the sample mean for the sequencex 1 ,...,xn+1can be expressed as a linear
combination of the sample mean at timenand the (n+1)stmeasurement. The
following R function codes this update formula:
mnupdate <- function(n,xbarn,xnp1){
# Input: n is sample size; xbarn is mean of sample of size n;
# xnp1 is (n+1) (new) observation
# Output: mean of sample of size (n+1)
mnupdate <- (n/(n+1))*xbarn + xnp1/(n+1)
return(mnupdate)
}
To run this function we first source it in R. If the function is in the filemnupdate.R
in the current directory then the source command issource("mnupdate.R").It
can also be copied and pasted into the current R session. Here is an execution of it:
> source("mnupdate.R")
> x = c(3,5,12,4); n=4; xbarn = mean(x);
> x; xbarn #Old sample and its mean
[1] 3 5 12 4

[1] 6

> xp1 = 30 # New observation
> mnupdate(n,xbarn,xp1) # Mean of updated sample
[1] 10.8

B.4 Loops


Occasionally in the text, we use a loop in an R program to compute a result. Usually
it is a simpleforloop of the form
for(i in 1:n){
... R code often as a function of i ...
# For the n-iterations of the loop, i runs through
# the values i=1, i=2, ... , i=n.
}
For example, the following code segment produces a table of squares, cubes, square-
roots, and cube-roots, for the integers from 1 ton.

set n at some value


tab <- c() # Initialize the table
for(i in 1:n){
tab <- rbind(tab,c(i,i^2,i^3,i^(1/2),i^(1/3)))
}
tab

Free download pdf