Basic loop index in a function - r

I want to add a loop to the code below so that it runs four times for
n <- c(1000, 10000, 100000, 1000000)
And to return a matrix that contains n values and its solution pi? Thanks!
Here is my code for a single value of n:
n <- 1000
x <- c(runif(n, -1,1))
y <-c(runif(n, -1,1))
points <- data.frame(cbind(x,y))
z <- points$x^2 + points$y^2
pi <- function(n,points){
y <- 4*length(z[z<=1])/n
return(y)
}
pi(n, points)

here is a way where you use an implicit loop (sapply) instead of a for loop:
calc_pi <- function(n){
x <- c(runif(n, -1,1))
y <-c(runif(n, -1,1))
points <- data.frame(cbind(x,y))
z <- points$x^2 + points$y^2
pi <- function(n,points){
y <- 4*length(z[z<=1])/n
return(y)
}
pi(n, points)
}
n <- c(1000, 10000, 100000, 1000000)
set.seed(1)
data.frame(n = n, pi = sapply(n, calc_pi))
n pi
1 1e+03 3.080000
2 1e+04 3.141600
3 1e+05 3.137640
4 1e+06 3.143064
Note that it is good practice to set a random seed with set.seed when working with random numbers (see e.g. this question).

Related

Make datasets by loop in R

I'm trying to learn how to make a loop in R
I have this:
sigma2 <- 0.4
a0 <- -0.1260805
b <- 0.1260805
tt <- 1:50, 1:50
z <- rnorm(50, 0, sigma2)
y <- rep(1, 50)
for(i in 1:50){
y[i]=exp(a0 + b*tt[i])*exp(z[i])
}
y
and I want to kind of test the code above 1000 times, since I want to test the hypothesis at the 0.05 level
can I treid this, and seens to be wrong:
aa <- rep(1, 1000)
for(i in 1:1000){
y[i]=exp(a0 + b1*tt[i])*exp(z[i])
}
Thanks for help!
I think this is what you want (or at least closer):
# re-write original code with vectorization:
n <- 50
sigma2 <- 0.4
a0 <- -0.1260805
b <- 0.1260805
tt <- 1:n
z <- rnorm(n, 0, sigma2)
y <- exp(a0 + b*tt)*exp(z)
# do it 20 times
result <- replicate(20, exp(a0 + b*tt)*exp(rnorm(n, 0, sigma2)))
result is a 50x20 matrix - one column per repetition.

Generating data and saving estimates in a loop in R

I'm a beginner with R and programming in general and i'm having some problems with this loop.
Basically i want to generate 10,000 estimates of beta_2 when n=10 and store them in a vector where the estimator in question is given by the formula (cov(x,y)/var(x)).
Ive tried the following code but it only yields the first estimate correctly and fills the other positions in the vector as NA. Any tips to solve this?
X <- rlnorm(n, X_meanlog, X_sdlog)
u <- rnorm(n, u_mean, u_sd)
Y <- beta_1 + beta_2 * X + u
rep <- 10000
vect <- vector(mode="numeric", length=rep)
for(i in 1:rep){vect[i] <-(cov(X,Y) / var(X))[i]}
You must simulate the vectors X and Y inside the loop.
n <- 10
X_meanlog <- 0
X_sdlog <- 1
u_mean <- 0
u_sd <- 1
beta_1 <- 2
beta_2 <- 3
set.seed(5276) # Make the results reproducible
rept <- 10000
vect <- vector(mode="numeric", length=rept)
for(i in 1:rept){
X <- rlnorm(n, X_meanlog, X_sdlog)
u <- rnorm(n, u_mean, u_sd)
Y <- beta_1 + beta_2 * X + u
vect[i] <- (cov(X, Y) / var(X))
}
mean(vect)
#[1] 3.002527
You can also run the following simpler simulation.
set.seed(5276) # Make the results reproducible
X <- replicate(rept, rlnorm(n, X_meanlog, X_sdlog))
u <- replicate(rept, rnorm(n, u_mean, u_sd))
Y <- beta_1 + beta_2 * X + u
vect2 <- sapply(seq_len(rept), function(i)
cov(X[, i], Y[, i]) / var(X[, i])
)
mean(vect2)
#[1] 3.001131

Obtain 1000 confidence interval from t.test

x <- c(1:100)
y <- c(89:300)
s1 <- sample(x, 30)
s2 <- sample(y, 30)
mytest <- t.test(s1, s2)
mytest$conf.int
I would like to run this 1000 times and create a matrix with the 1000 intervals obtained. I have tried some loops but every time I am getting the same 1000 intervals. However, every time it should give me a different interval since I am sampling each time before performing the t.test.
You can do this with replicate:
x <- c(1:100)
y <- c(89:300)
myCI = function(x,y) {
s1 <- sample(x, 30)
s2 <- sample(y, 30)
mytest <- t.test(s1, s2)
mytest$conf.int
}
CIs = t(replicate(1000, myCI(x,y)))

Repeating a for loop in R

Suppose I have a 10 x 10 matrix. I want to randomly choose 2 numbers from each column and take the square of the difference of these numbers. I wrote the R code for that and I get 10 values, but I wish to repeat this, say, 100 times, in which case I need to get 100*10=1000 numbers. How could I do that?
x <- rnorm(100)
m <- 10
n <- 10
X <- matrix(x,m,n)
for (i in 1:m ) {
y <- sample(X[,i],2,rep=F)
q2[i] <- (y[1]-y[2])^2
}
Or as #Davide Passaretti and #nrussell mentioned in the comments, you can use replicate
f1 <- function(x, m){
q2 <- vector(mode='numeric', length= m)
for(i in 1:m){
y <- sample(x[,i], 2, rep=FALSE)
q2[i] <- (y[1]-y[2])^2
}
q2
}
n <- 100
res <- replicate(100, f1(X, m))
prod(dim(res))
#[1] 1000

Generate a sequence by formula with R

I want to generate a sequence:
X_n= |X_{n-1} - epsilon_n|,
where epsilon_n has an exponential distribution.
For example
epsilon <- rexp(100, rate = 0.3)
Use Reduce:
X0 <- 10
set.seed(42)
epsilon<-rexp(100, rate = 0.3)
eps <- c(X0, epsilon)
X <- Reduce(function(x, y) abs(x-y), eps, accumulate = TRUE)
plot(X)
## n is length of the sequence, X0 is initial value,
## default exponential rate is 0.3
xSeq <- function(n,X0,rate=0.3){
vOut <- rep(0,n)
vOut[1] <- X0
eSeq <- rexp(n-1,rate)
for(i in 2:n){
vOut[i] <- abs(vOut[i-1]-eSeq[i-1])
vOut
}
return(vOut)
}

Resources