for loop with if else statement in R - r

I know lots of people have posted about this, and I did look through the answers to write my code, but it's still not working... Can someone point out where i'm doing wrong please? many thanks in advance!
for(j in 1:1000){
for(i in 1:52){
if (i == 1){
r.sims[i,] <- r.sims[1]
}
else if (i == 2){
r.sims[i,] <- r.sims[2]
}
else (i > 2){
r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
}
}
}
i have the following errors
Error: unexpected '{' in:
" }
else (i > 2){"
> r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
Error in r.sims[i, ] <- r.sims[i - 1, ] * ar1 + r.sims[i - 2, ] * ar2 + :
replacement has length zero
> }
Error: unexpected '}' in " }"
>
> }
Error: unexpected '}' in " }"
>
> }
Error: unexpected '}' in " }"
>

Without understanding what your code is supposed to do, I have nevertheless made an example of how you might fix your script. I think the key is that you need to supply curly brackets {...} following your else statement in order for it to consider the following code.
Example:
r.sims <- matrix(runif(52)*100, nrow=52, ncol=100)
e.sims <- matrix(runif(52)*100, nrow=52, ncol=100)
ma1 <- 1
ar1 <- 2
ar2 <- 3
for(j in 1:1000) {
for(i in 1:52) {
if (i == 1) {
r.sims[i,] <- r.sims[1]
} else {
if(i == 2) {
r.sims[i,] <- r.sims[2]
} else {
if(i > 2) {
r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
}
}
}
}
}

You seem to misunderstand the concept of else.
else covers all cases that didn't match previous if or else if statements.
Therefore, you cannot specify any condition for else.
To cover all cases where i is not 1 or 2 simply use else, without any () brackets.
If you want to have a condition, use else if (condition).

Related

Why can't my function find arguments?

I'm trying to do a function that performs the bisection method. But I get a lot of errors that I don't understand. The code is:
bisection<-function(f,a,b,n=1000,tol=1e-9)
{
if(!(f(a)<0) && (f(b)>0)){stop};
elseif((f(a)>0) && (f(b)<0)){stop};
for (i in 1:n){
c=(a+b)/2;
if((f(c)==0)||((b-a)/2)<tol){return(c)};
elseif(sign(f(c))==sign(f(a)),a<-c,b<-c);
}
}
and I get the following from R:
> bisection<-function(f,a,b,n=1000,tol=1e-9)
+ {
+ if(!(f(a)<0) && (f(b)>0)){stop};
+ elseif((f(a)>0) && (f(b)<0)){stop};
Error: unexpected '{' in:
" if(!(f(a)<0) && (f(b)>0)){stop}
elseif((f(a)>0) && (f(b)<0)){"
> for (i in 1:n){
+ c=(a+b)/2;
+ if((f(c)==0)||((b-a)/2)<tol){return(c)};
+ #elseif(sign(f(c))==sign(f(a)),a<-c,b<-c);
+ }
Error: object 'n' not found
> }
Error: unexpected '}' in "}"
I would be most grateful if someone could point out what I've done wrong.
Thank you in advance!
I tried to correct your function. So it does not result in errors:
bisection<-function(f,a,b,n=1000,tol=1e-9)
{
if(!(f(a)<0) && (f(b)>0)){stop}
else if((f(a)>0) && (f(b)<0)){stop}
for (i in 1:n){
c=(a+b)/2
if((f(c)==0)||((b-a)/2)<tol){
return(c)
}
else if(sign(f(c))==sign(f(a))){
a<-c
b<-c
}
}
}
but I guess you want another else case in the last else if:
bisection<-function(f,a,b,n=1000,tol=1e-9)
{
if(!(f(a)<0) && (f(b)>0)){stop}
else if((f(a)>0) && (f(b)<0)){stop}
for (i in 1:n){
c=(a+b)/2
if((f(c)==0)||((b-a)/2)<tol){
return(c)
}
else if(sign(f(c))==sign(f(a))){
a<-c
}else{
b<-c
}
}
}
Furthermore, it looks like you confused the concept of ifelse with else if.
See for ifelse: https://www.datamentor.io/r-programming/ifelse-function
and else if: https://www.datamentor.io/r-programming/if-else-statement

R guessing game syntax

I'm having trouble with proper bracket syntax when making a guessing game. Here is a brief example of my code
number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
input <- 0
rand <- sample(seq(1,100), size = 1)
input = number_result
while(input != rand){
if(input < rand){
print("Higher!")
}
else if(input > rand){
print("Lower!")
}
else(input = rand){
return(print("You got it!"))
}
}
My error is:
Error: unexpected '{' in:
" }
else(input = rand){"
> return(print("You got it!"))
[1] "You got it!"
Error: no function to return from, jumping to top level
> }
Error: unexpected '}' in "}"
> }
Error: unexpected '}' in " }"
>
No return needed because you didn't define a function. You must also specify a stopping condition! Otherwise your while will run forever.
try this
number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
input <- 0
rand <- sample(seq(1,100), size = 1)
input = number_result
while(input != rand){
if(input < rand){
print("Higher!")
} else if(input > rand){
print("Lower!")
} else {
print("You got it!")
}
input <- input + 1
}

Why can't I use in with an if condition

I have the following code:
x=rnorm(100,0,1)
x
a=0
for(i in x){
if(i in -1:1){
a<-a+1
}
}
I'm getting the following error:
Geeting error unexpected '}' in " }"
What am I doing wrong?
I changed the condition in the if statement. Is this what you want?
x=rnorm(100,0,1)
x
a = 0
for(i in x){
if(i > -1 & i < 1){
a <- a + 1
}
}

Use result of previous loop as input for next loop

I have the code below, which seems to accomplish what I'm trying to do but also throws the error output shown below the code. What I'm trying to do, is run through the loop the first time with x = 1, then for each time the loop runs after that I want x = y, the result of the previous loop. I always fumble with loops so any tips are greatly appreciated.
Code:
for(i in 1:5)
{
if(i=1)
{
x<-1
}
else
{
x<-y
}
y<-x*i
y
}
ERRORS:
for(i in 1:5)
+ {
+ if(i=1)
Error: unexpected '=' in:
"{
if(i="
> {
+ x<-1
+ }
> else
Error: unexpected 'else' in " else"
> {
+ x<-y
+ }
> y<-x*i
> y
[1] 25
> }
Error: unexpected '}' in "}"
Here is your code re-written with slightly clearer syntax
for (i in 1:5) {
if (i == 1) {
x <- 1
} else {
x <- y
}
y <- x * i
}
Or even better syntax.
for (i in 1:5) {
x <- ifelse(i == 1, 1, y)
y <- x * i
}

KnapSack dynamic programming in R with recursive function

I created this simple code in R to solve the Knapsack program with a recursive funtion
n <- c(0,1,2,3,4)
v <- c(10,40,30,50)
w <- c(5,4,6,3)
k <- 10
myfunction <- function(n,k){
if (n==0 | k==0){
output <- 0
} else if (w[i] > k) {
output <- myfunction[i-1,w]
} else {
output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
}
return(myfunction)
}
However, I don't get a value as an output, but the whole function. For example if I put in:
myfunction(4,10)
I don't get an value of 90, but the whole funtion typed out.
these are the values
There were several errors beyond the ones pointed out by #etienne. Here's an annotated debugging session. First we fix the returned object:
> myfunction <- function(n,k){
+ if (n==0 | k==0){
+ output <- 0
+ } else if (w[i] > k) {
+ output <- myfunction[i-1,w]
+ } else {
+ output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
+ }
+ return(output)
+ }
> myfunction(4,10)
Error in if (w[i] > k) { : argument is of length zero
Obviously neither w nor k are of length zero which suggests it must be i. (As also pointed out by etienne). Looking at your code it appears you actually intended i to be the index that decreased until the terminating condition was met. So replace n by i in the few instances where it appeared:
> myfunction <- function(i,k){
+ if (i==0 | k==0){
+ output <- 0
+ } else if (w[i] > k) {
+ output <- myfunction[i-1,w]
+ } else {
+ output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
+ }
+ return(output)
+ }
> myfunction(4,10)
Error in myfunction[i - 1, w] :
object of type 'closure' is not subsettable
So you also made the mistake of using square-brackets where parentheses (aka bracket in the non-US sections of the world) were needed:
> myfunction <- function(i,k){
+ if (i==0 | k==0){
+ output <- 0
+ } else if (w[i] > k) {
+ output <- myfunction(i-1,w)
+ } else {
+ output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
+ }
+ return(output)
+ }
> myfunction(4,10)
[1] 90
Success, well, almost. Most of the warnings are because you used | instead of || in one of the conditionals:
Warning messages:
1: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
2: In if (w[i] > k) { :
the condition has length > 1 and only the first element will be used
3: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
4: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
5: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
6: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
So replace that instance with a logical ||. To deal with the other warning that didn't seem to sabotage your logic, realize that w[i] is length-0 when i == 0, so add a logical clause in the conditional that first tests for that possibility and use the correct "double-AND-sign" ( && ):
myfunction <- function(i,k){
if (i==0 || k==0){
output <- 0
} else if (length( w[i]) && w[i] > k) {
output <- myfunction(i-1,w)
} else {
output <- max(v[i]+ myfunction(i-1, k-w[i]), myfunction(i-1,k))
}
return(output)
}
Now you get:
> myfunction(4,10)
[1] 90

Resources