R - Print values using for, while, and repeat loop - r

I am having trouble again with my code. Here is the question and what I have right now:
# 2. Draw a random sample of size n=20 from a uniform distribution in 0 and 1 using
# runif(20). Sequentially, print values using the following rules:
# i. Print a value if it is less than 0.3 or more than 0.8, but skip it
# (don’t print the value) if it is in (0.1, 0.2],
# ii. Skip the entire process if you find a value in [0.4,0.5].
# Write three separate R codes using (a) for loop, (b) while loop
# and (c) repeat loop.
# (a) for loop
n = runif(20)
for (val in n){
if (val > 0.1 & val <= 0.2){
next
} else if (val < 0.3 | val > 0.8){
print(val)
} else if (val >= 0.4 & val <= 0.5){
print(val)
break
}
}
# (b) while loop
n = 1
m = runif(20)
while(n < 20){
if (m > 0.1 & m <= 0.2){
next
} else if (m < 0.3 | m > 0.8){
print(m)
} else if (m >= 0.4 & m <= 0.5){
print(m)
break
}
n = n + 1
}
# (c) repeat loop
n = 1
m = runif(20)
repeat{
if (m > 0.1 & m <= 0.2){
next
} else if (m < 0.3 | m > 0.8){
print(val)
} else if (m >= 0.4 & m <= 0.5){
print(m)
break
}
}
Part (a) for loop is working perfectly.
My only issue is (b) while loop and (c) repeat loop. He didn't do a good job in class or notes going over a while loop and repeat loop. Please help.

The object m that you created has a length of 20, so when you go to test it with something like if (m > 0.1 & m <= 0.2), R only tests the first item in your object. To solve this, you'll need to index m with n, your loop counter. In other words, don't use m in your tests, but use m[n] instead. In all it should look like this:
n <- 1
m <- runif(20)
while(n < 20){
if (m[n] > 0.1 & m[n] <= 0.2){
next
} else if (m[n] < 0.3 | m[n] > 0.8){
print(m[n])
} else if (m[n] >= 0.4 & m[n] <= 0.5){
print(m[n])
break
}
n <- n + 1
}
You should be able to use a similar approach for part c. (Also note that in part c you have print(val) at one point.)
Hope that helps!

Apparently the exercise if for you to sort it out, but OK, I'll post a solution.
# (b) while loop
n = 1
m = runif(20)
while(n <= 20){
if (m[n] > 0.1 & m[n] <= 0.2){
n = n + 1
next
} else if (m[n] < 0.3 | m[n] > 0.8){
print(m[n])
} else if (m[n] >= 0.4 & m[n] <= 0.5){
print(m[n])
break
}
n = n + 1
}
# (c) repeat loop
n = 0
m = runif(20)
repeat{
if(n < 20)
n <- n + 1
else
break
if (m[n] > 0.1 & m[n] <= 0.2){
next
} else if (m[n] < 0.3 | m[n] > 0.8){
print(m[n])
} else if (m[n] >= 0.4 & m[n] <= 0.5){
print(m[n])
break
}
}
As a final note, whenever pseudo-random number generators are used you should set the initial value in order for the results to be reproducible. This is done like this:
set.seed(6019) # or any other value, 6019 is the seed
This is put before the first call to runif.

Related

Prime number generator using for loop in R

Trying to create a for loop in which you input a number and the function tells you whether or not the number is prime or not. I used two examples being n1 <- 100 and n2 <- 101.
Here is my code below:
n1 <- 100
n2 <-101
answer = TRUE
for(i in n1){
if (n1 %% (i-1) == 0){
prime1=FALSE
}else {
prime1=TRUE
}
}
prime1
answer = TRUE
for (i in n2){
if (n2 %% (i-1) == 0){
prime2=FALSE
}else {
prime2=TRUE
}
}
prime2
The problem is that the function will generate the same output for both depending on one difference in the code.
In the first "if" statement, both functions will generate output TRUE if I put in the line (i-1). However, if I instead change the line of code to "n1 %% i == 0" as opposed to "n1 %% (i-1) == 0", both functions generate the output FALSE.
Any pointers? Thanks!
Here's a simple prime checker using a for loop.
With n1 <- 100 :
for(i in seq(2, ceiling(sqrt(n1)))) {
if(n1 %% i == 0){
print(FALSE)
break
}
if(i == ceiling(sqrt(n1)))
print(TRUE)
}
#> [1] FALSE
With n2 <- 101
for(i in seq(2, ceiling(sqrt(n2)))) {
if(n2 %% i == 0){
print(FALSE)
break
}
if(i == ceiling(sqrt(n2)))
print(TRUE)
}
#> [1] TRUE

How does one elegantly initialize start values or parameter values when creating a julia JuMP parameter or variable container?

Was hoping a Julia or JuMP expert could help me on how to do the following (apologies as I am new to the language and tried all resources but cannot find a solution to this problem)
I am trying to initialize the start values of all variables when creating a JuMP variable container.
I have a function defined as follows:
function sam(i, j)
if i == "BRD" && j == "CAP"
return 5
elseif i == "BRD" && j == "LAB"
return 10
elseif i == "MLK" && j == "CAP"
return 20
elseif i == "MLK" && j == "LAB"
return 15
elseif i == "CAP" && j == "HOH"
return 25
elseif i == "HOH" && j == "BRD"
return 15
elseif i == "HOH" && j == "MLK"
return 35
else
return nothing
end
end
I want to initialize a couple model variables, let's say household consumption of a product.
#variable(model, 0.001 <= Xᵢ[h, g]) # where h = ["HOH"] and g = ["BRD", "MLK"]
This variable can be initialized using the function above. It should be "HOH" -> "BRD" and "HOH" -> "MLK". So 15 and 35 respectively.
I can do these initializations by doing this:
set_start_value(Xᵢ["HOH", "BRD"], sam("HOH", "BRD"))
set_start_value(Xᵢ["HOH", "MLK"], sam("HOH", "MLK"))
However, I was hoping there would be a better way to do this using the start option. I have tried the following with no success.
#variable(model, 0.001 <= Xᵢ[h, g], start = sam(h, g)) # option 1
#variable(model, 0.001 <= Xᵢ[h, g], start = sam.(h, g)) # option 2
#variable(model, 0.001 <= Xᵢ[h, g], start = sam.(permute(h), g)) # option 3
#variable(model, 0.001 <= Xᵢ[h, g], start = [sam(h,g) for h in h, for g in g]) # option 4
The same question similarly applies to the creation of #NLparameter`. How can one do this for a parameter. Options tried below:
#NLparameter(model, 0.001 <= FFᶠ[f][h] == sam(f, h))
#NLparameter(model, 0.001 <= FFᶠ[f][h] == sam.(f, h))
#NLparameter(model, 0.001 <= FFᶠ[f][h] == sam.(permute(f), h))
#NLparameter(model, 0.001 <= FFᶠ[f][h] == [sam(f,h) for f in f, for h in h])
A simpler example:
I have some function f = x^2 + y^2 and arrays x=[1,2,3,4,5,6] and y=[1,2,3,4,5,6] how can I write:
#variable(model, v[x,y], start=f(x,y))
Such that value(v[1, 2]) start value will be equal to 1^2 + 2^2 therefore 5.
Do something like:
julia> using JuMP
julia> h, g = ["HOH"], ["BRD", "MLK"]
(["HOH"], ["BRD", "MLK"])
julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.
julia> function sam(i, j)
if i == "HOH" && j == "BRD"
return 15
else
return nothing
end
end
sam (generic function with 1 method)
julia> #variable(model, 0.001 <= X[i=h, j=g], start = sam(i, j))
2-dimensional DenseAxisArray{VariableRef,2,...} with index sets:
Dimension 1, ["HOH"]
Dimension 2, ["BRD", "MLK"]
And data, a 1×2 Matrix{VariableRef}:
X[HOH,BRD] X[HOH,MLK]
julia> start_value.(X)
2-dimensional DenseAxisArray{Union{Nothing, Float64},2,...} with index sets:
Dimension 1, ["HOH"]
Dimension 2, ["BRD", "MLK"]
And data, a 1×2 Matrix{Union{Nothing, Float64}}:
15.0 nothing
I guess we could make this more explicit in the documentation. I've opened an issue to get this fixed: https://github.com/jump-dev/JuMP.jl/issues/3147

Create sequence in R

Hi I was wondering if someone knows how to realize this sequence in R?
Consider a sequence with following requirement.
a1=1
an=an-1+3 (If n is a even number)
an=2×an-1-5 (If n is a odd number)
e.g. 1,4,3,6,7,10,15,...
a30=?
Try the following.
It will return the entire sequence, not just the last element.
seq_chih_peng <- function(n){
a <- integer(n)
a[1] <- 1
for(i in seq_along(a)[-1]){
if(i %% 2 == 0){
a[i] <- a[i - 1] + 3
}else{
a[i] <- 2*a[i - 1] - 5
}
}
a
}
seq_chih_peng(30)
Note that I do not include code to check for input errors such as passing n = 0 or a negative number.
If you want to do it recursively, you just have the write the equations in your function as follows:
sequence <- function(n) {
if (n == 1) return(1)
else if (n > 1) {
if (n %% 2 == 1) {
return(2 * sequence(n - 1) - 5)
}else{
return(sequence(n - 1) + 3)
}
}else{
stop("n must be stricly positive")
}
}
sequence(30)
# returns 32770

Applying a user defined R codes to a data set

I have R codes that I would like to apply to a data file. Please see the codes below:
library(plyr);
library(dplyr);
ability<- function(mdl, u, b, a, c){
J<- length(b)
if(mdl == 1 | mdl==2 | missing(c)) {
c<- rep(0,J)
}
if (mdl == 1 | missing(a)) { a<- rep(1,J)}
x<- sum(u)
if (x == 0) {
th<- -log(2*J)
}
if(x == J){
th<- log(2*J)
}
if (x == 0 | x == J) {
sumdem<- 0.0
for ( j in 1:J) {
pstar<- 1/(1 + exp(-a[j] * (th - b[j])))
phat<- c[j] + (1.0 - c[j])* pstar
sumdem<- sumdem - a[j]**2 * phat * (1.0 - phat) * (pstar / phat)**2
}
se <- 1/ sqrt(-sumdem)
}
if (x != 0 & x != J){
th<- log(x /(J-x))
S<- 10;
ccrit <- 0.001
for ( s in 1:S) {
sumnum <- 0.0
sumdem <- 0.0
for(j in 1:J){
pstar<- 1/(1 + exp(-a[j] * (th - b[j])))
phat<- c[j] + (1.0 - c[j])* pstar
sumnum<- sumnum + a[j] * (u[j] - phat) *
(pstar / phat)
sumdem <- sumdem - a[j]**2 * phat * (1.0 - phat) *
(pstar / phat)**2
}
delta<- sumnum / sumdem
th<- th - delta
if(abs(delta) < ccrit | s == S) {
se<- 1/sqrt(-sumdem)
break;
}
}
}
cat(paste("th=", th, "\n")); flush.console();
cat(paste("se=", se, "\n")); flush.console();
thse<- c(th, se);
return(thse);
}
u<-read.csv("C:\\PA\\Keystone\\Spring 018\\data\\out_sp16_ALGEBRA1.csv",header=TRUE,as.is=T);
b<- c(-0.5255,0.0645,-0.0685,0.4132,0.5103,0.6826,-0.524,-0.2108,-0.3115,0.583,-0.6093,1.1567,0.6096,-0.2789,0.1151,1.2127,-0.085,-0.2494,-0.2724,0.0433,-0.4693,0.1692,0.15,0.3255,0.6008,0.3654,-1.239,-0.7911,0.2886,0.2324,0.1885,0.6671,-0.1561,0.4412,1.4597,0.0981,0.2668,1.9483,2.0044,1.403,2.1106,1.0472);
a<- rep(1,length(b));
u<-u[,-c(1)]
u<-as.matrix(u)
apply()
The argument u is a data set that I converted to matrix and would like to apply the codes to all row of the matrix. a is a vector and b is a vector. I thought about using apply() but not giving me what I want.
Thanks for your time and input.
I am assuming that each row of the u represents different students and each column represents different items so using matrix indices may help(i.e sum(u[1,]) will compute sum for overall performance or all items combined for 1st student. also I did not get what you are asking specifically in order to guide what you should do.

Simulate from a distribution function using Rejection Method

I am trying to simulate data 10000 observations for the following distribution:
{ 3x(1-x)2 0 < x < 1
f(x) = { 3(2-x)(1-x)2 1 ≤ x < 2
{ 0 otherwise
Using the rejection method, I am boxing the distribution by the following rectangle: x=0,x=2,y=0,y=2
However, there is some fault in my code below as it doesn't seem to work. Can any one please advise on a fix?
n=10000
t=0
x=0
while(t<n)
{u=runif(1,0,2)
y=runif(1,0,2)
if {(u in c(0:1))
fun=3*u*(1-u)^2
else (u in c(1:2))
fun=3*(2-u)*(1-u)^2}
if (y<fun)
{t=t+1
x[t]=u}}
You have a bunch of R syntax errors. You should review a basic R introduction. be careful with placement of braces. Also there is no in keyword in R.
n <- 10000
t <- 0
x <- 0
while(t<n) {
u <- runif(1,0,2)
y <- runif(1,0,2)
if (u > 0 & u < 1) {
fun <- 3*u*(1-u)^2
} else if (u >= 1 & u < 2) {
fun <- 3*(2-u)*(1-u)^2
} else {
fun <- 0
}
if (y<fun){
t <- t+1
x[t] <- u
}
}

Resources