Professional Documents
Culture Documents
Basic Commands:
# combine
2^x
x <- 1:100
x = x^2
y <- c(5, 12, 17)
x[y]
a <- x > 12
Basic Functions:
n <- length(x)
f <- rep(1/n, n)
myvar(x, f)
y <- runif(50, 0, 8)
f <- y/sum(y)
myvar(x, f)
4
Standard Deviation:
mysd <- function(v) {
n <- length(v)
m <- mean(v)
S <- 0
for (i in 1:n) {
S = S + (v[i] - m)^2
}
result <- sqrt(S/(n - 1))
}
g4 <- c()
for (i in 1:500) {
group4 <- sample(v2, 4, replace = T)
m <- mean(group4)
g4 <- c(g4, m)
}
s2 <- mysd(g4)
m <- mean(group25)
g25 <- c(g25, m)
}
s3 <- mysd(g25)
6
n <- 1e+06
x <- c()
S <- 0
for (i in 1:n) {
x <- 240 * runif(1)
S <- S + (x - 120)^2
}
sigma <- sqrt(S/n)
# Alternative
n <- 1e+06
x <- runif(n, 0, 240)
sigma <- sqrt(sum((x - 120)^2)/n)
7
Combination:
n <- 50
p <- 0.7
x <- 0:n
y <- choose(n, x) * p^x * (1 - p)^(n - x)
plot(x, y, "h", lwd = 4, col = "red")
10
# 03.11.2022
N <- 500
k <- 100
n <- 100
x <- 0:n
p <- k/N
y <- hyperg(N, n, k, x)
plot(x, y, "l", col = "red", lwd = 4)
y2 <- binom(n, p, x)
lines(x, y2, "l", col = "blue", lwd = 4)
11
rows <- 16
M <- c()
for (k in (2:10)) {
lambda <- k/2
p <- exp(-lambda)
v = c(p)
for (i in (1:rows)) {
p = p + exp(-lambda) * lambda^i/factorial(i)
v = c(v, p)
}
v <- round(10000 * v)/10000
M <- cbind(M, matrix(v, ncol = 1))
}
M <- cbind(0:rows, M)
M <- rbind(seq(0.5, 5, 0.5), M)
M
13
n = 7.5
v = c()
p = 0
i = 0
while (p < 0.99995) {
p = p + exp(-n) * n^i/factorial(i)
v = c(v, p)
i = i + 1
}
v = round(10000 * v)/10000
M = cbind(0:i, v)
M
14
mu <- 50
sigma <- 10
x <- seq(0, 100, 0.1)
y = exp(-(x - mu)^2/(2 * sigma^2))/(sigma * sqrt(2 * pi))
plot(x, y, "l")
Gamma Distribution:
}
17
Sort a Vector v:
List of Primes:
Correlation:
S <- 0
S <- 1
for (i in 3:n) {
flag <- 1
for (j in 2:(i - 1)) {
if (i %% j == 0) {
flag = 0
break
}
}
S = S + flag
}
return(S)
}
23
Combination:
rp <- 1
k <- min(n,m)
for (i in 2:k){
if(n %% i == 0 & m %% i == 0){
rp <- 0
}
}
return(rp)
}
A <- c()
for (i in 1:n){
for (j in i:n){
k <- sqrt(i^2 + j^2)
if (floor(k) == ceiling(k) & RelPrime(i,j)){
v <- c(i,j,k)
A <- rbind(A,v)
}
}
}
return(A)
}
26
Sampling Distribution:
n <- 100000
x <- 0:100
y <- rep(0,101)
tot <- c()
for (i in 1:n){
S <- sum(round(runif(100)))
y[S] = y[S] + 1
tot <- c(tot,S)
}
m <- 4
z4 <- rep(0,101)
for (i in 1:n){
v <- round(runif(m,1,n))
S <- sum(tot[v]) / m
z4[S] = z4[S] + 1}
m <- 9
z9 <- rep(0,101)
for (i in 1:n){
v <- round(runif(m,1,n))
S <- sum(tot[v]) / m
z9[S] = z9[S] + 1}
Confidence Interval:
n <- 10000
#mu: 120
#sigma: 120/sqrt(3)
#conf: 95%
#z:1.96
$sample size: 25
#120 - 1.96 * 120/(5 * sqrt(3)) = 92.84
#120 + 1.96 * 120/(5 * sqrt(3)) = 147.16
success <- 0
for (i in 1:n) {
x <- runif(25, 0, 240)
xbar <- mean(x)
if (92.84 <= xbar & xbar <= 147.16) {
success <- success + 1
}
}
success/n
28
Gambler’s Ruin:
N <- 100
n <- 58
S <- 0
for (i in 1:1000) {
x <- n
while (x < N && x > 0) {
if (runif(1) < 0.5) {
x = x - 1
} else {
x = x + 1
}
}
if (x == N) {
S <- S + 1
}
}
print(S/1000)