Introduction to R Part II
Wanhua Su
9/20/2022
1 Generate Observations from a Given Distribution
R has four types of functions for getting information about a family of distributions.
(1) d function: return the pdf of the distribution;
(2) p function: return the cdf of the distribution;
(3) q function: return the quantiles;
(4) r function: return random observations.
The distribution names are:
(1) binomial distribution: binom
(2) poisson distribution: pois
(3) normal distribution: norm
(4) t-distribution: t
(5) F-distribution: F
(6) χ2 -distribution: chisq
(7) gamma distribution: gamma
Combine the four functions to each name, then get the four functions for each distribution.
To generate observations from a distribution, use r followed by the function name.
rnorm(2,70,10) #2 observations from N(70,10)
## [1] 73.21697 74.41896
rt(3,15) #3 observations from t with df=15
## [1] 0.3076063 1.4470862 -0.5591743
1
2 Iterations in R
Similar to other languages, we can run iterations in R using for loop and while loop.
1) Print 1 to 5 using for loop and while loop
for (i in 1:5) cat("i=",i,"\n")
## i= 1
## i= 2
## i= 3
## i= 4
## i= 5
i=0
while (i<5){
i=i+1
cat("i=",i,"\n")
}
## i= 1
## i= 2
## i= 3
## i= 4
## i= 5
2) Calculate the sum of 1 to 5 using a for loop and while loop.
sum=0
for (i in 1:5) sum=sum+i
sum
## [1] 15
sum=0
i=0
while (i<5){
i=i+1
sum=sum+i
}
sum
## [1] 15
3 Write Your Own Function
We sometimes need to write our own function. For example, Write a function to standardize a vector to
have mean 0 and variance 1.
2
std=function(x){
#function to standardize a vector
#input: a vector
#output: a vector has mean 0 and variance 1
m=mean(x)
s=sqrt(var(x))
result=(x-m)/s
return(result)
}
We can try our function and compare the result with the one given by the built-in R function.
x=1:5 #generate a vector of 1 to 5
y=std(x) #apply the function
y
## [1] -1.2649111 -0.6324555 0.0000000 0.6324555 1.2649111
c(mean(y),var(y)) #get the mean and variance of the standardized vector
## [1] 0 1
(obj=scale(x)) #built-in function
## [,1]
## [1,] -1.2649111
## [2,] -0.6324555
## [3,] 0.0000000
## [4,] 0.6324555
## [5,] 1.2649111
## attr(,"scaled:center")
## [1] 3
## attr(,"scaled:scale")
## [1] 1.581139