R - When to add a break - r

I have an exercise that compares efficiency of loop functions.
I have function
banana <- function(x)
{d <- length(x)
xi <- x[1:(d-1)]
xnext <- x[2:d]
sum <- sum(100*(xnext-xi^2)^2 + (xi-1)^2)
y <- sum
return(y)
}
I want to re-write the above using a for loop (or any loop). I have so far
for (i in x){
n = length(x)
y <- 100*(x[i+1]-x[i]^2)^2 +(x[i]-1)^2
}
I want the function to stop at n-1 and having difficulty knowing where to add the break. Can someone help?
Thanks in advance,
Sean

You don't really have to add a break statement, you can just loop over all but the nth i.
[-length(x)] removes the last element from the sequence.
y <- 0
for (i in seq_along(x)[-length(x)]) {
y <- y + 100 * (x[i + 1] - x[i])^2 + (x[i] - 1)^2
}

Related

is it possible to use vector index in while function?

so i'm trying to create a fibonacci sequence and I found the following syntax which works
x <- 0
y <- 1
fib <- c()
while (x < 4000000 & y < 4000000){
x <- x + y
y <- x + y
fib <- c(fib, x, y)
}
However, this syntax only create the vector as long as the value of the x and y which is used in the calculation doesn't exceed 4,000,000. is it possible to makes the while refer to "if vector fib has less than let's say 100 element"?
thanks in advance
Making a very slight change to your code, use the length() function check the length (number of elements) of fib before each iteration of the while loop.
while(length(fib)<100){....}
This way you avoid creating a further variable to count the number of iterations, as in the other answers.
For what it's worth, this is how I would do it - a for loop is more appropriate as you have a set number of iterations
n <- 100
fib <- c(0,1)
for(i in 3:n){
fib[i] <- fib[i-2] + fib[i-1]
}
Here's another way to write the code -
fib <- numeric(100)
fib[1] <- 0
fib[2] <- 1
i <- 2
while (i < 100){
i = i + 1
fib[i] = fib[i-1] + fib[i-2]
}
Growing vector in a loop (fib = c(fib, x, y)) is inefficient so I have created a vector of fixed length (100) and then assigned the value to it. This also avoid creation of unnecessary temporary variables x and y.
Just define another variable for using inside the while loop and increase it by the length of the fib,
x <- 0
y <- 1
mylen <- 0 # new variable
fib <- c()
while (mylen<100){
x <- x + y
y <- x + y
fib = c(fib, x, y)
mylen <- length(fib)
}

loop in loop to calculate a sum of a "continuous product" sequence function in R

I try to calculate the value for the following equation in R.
I have the dataset and the value for each corresponding F_x, F_{x+1}...
However, as both Q and s have too many values, I am considering write a loop in loop. It's bit confused. As a loop for Q seems conflicting as the loop for s
But if I write loop as below, seems like I need to by hand calculate Q 100 times to get all of the answer. Also my loop seems to be wrong...How can I fix this problem? Thank you so much
Y <- function(x,s, Q){
n <- length(s-x)-1
Q <- c(1:100)
for(s in seq(1:n)){
Y[s] <- sum(s*Q[s]*cumprod(Fx[1:s]))
}
return(Y)
}
I am not sure if the code below reaches your objective
Y <- function(x,s) {
Q <- 1:100
S <- 1:(s-x)
outer(Q,S,FUN = function(q,s) q * sum(c(1:s) * cumprod(Fx[1:s])))
}
for loop version
Y <- function(x,s) {
nr <- 100
nc <- s-x
y <- matrix(nr*nc,nrow = nr)
for (Q in 1:nr) {
for (S in 1:nc) {
y[Q,S] <- Q * sum(c(1:S) * cumprod(Fx[1:S]))
}
}
y
}

Extracting repetition index from apply / map loop

I'm trying wherever possible to replace my for loops with apply / map functions
However I am stuck when it comes to times where I need to use the loop index as a position. This is easy to do with a for loop
Take the following code, I use the index i in both the left hand and the right hand side of the assignment:
score <- function(x) {
n <- length(x)
right <- x
for(i in 1:n) {
right[i] <- (n - x[i] + 1) / (i * n)
}
(1 / n) * sum(right)
}
score(c(2,1,3))
how do i rewrite the above using map or apply functions?
You could use this:
x = c(2,1,3)
n = length(x)
(1/n) * sum(sapply(1:n, function(i) (n - x[i] + 1)/(i*n) ))
We could vectorize this
v1 <- c(2, 1, 3)
n <- length(v1)
(1/n) *sum((n - v1 + 1)/(seq_along(v1) * n))
#[1] 0.4259259

How to compute the sum of a vector in r using a for loop

I would like to ask how I can compute the sum of a vector in R without using one of the the ready functions (sum, mean etc). Sorry for the silly question!!!
I tried the following but it did not work. Could you tell me what I am doing wrong?
The code is:
x<-c(1,2,3)
sumfun<-function(y){
sum<-0
for(i in 1:(length(y)-1)){
sum=sum+y[i]
}
print(sum)
}
sumfun(x)
These each return the sum of the elements in x:
Sum <- 0
for(x_ in x) Sum <- Sum + x_
Sum
Sum <- 0
for(i in seq_along(x)) Sum <- Sum + x[i]
Sum
Reduce(`+`, x)
# recursive solution
summer <- function(x) if (length(x) > 0) x[1] + Recall(x[-1]) else 0
summer(x)
sum(x)
# limited as it assumes x has three elements
x[1] + x[2] + x[3]
You should change the range of your for loop to make it read the values of the first up until the last index, thus remove the -1 in for(i in 1:(length(y)-1)). The fix makes the entire code look like:
x<-c(1,2,3)
sumfun<-function(y){
sum<-0
for(i in 1:(length(y))){
sum=sum+y[i]
}
print(sum)
}
sumfun(x)
This should print out 6.

Summing over a range of value in R (not using for loop)

How do you perform such summation in R?
sum_{i=1}^3 (x^2)
i=1 is lower bound
i=3 is upper bound
x^2 is the operation
So we will perform
1^2 + 2^2 + 3^2
Using standard loop:
tot <-0
for (x in 1:3) {
tot <- tot + x^2
}
First, I'll point out that to generate a vector containing the elements 1,2,3 you can do:
x <- 1:3
Secondly, R is a vectorised language - meaning if x is a vector and I do x + 5 it'll add 5 to each element of x for me without needing a for loop.
# Recalling that "x <- x + 5" is the same as
for ( i in 1:length(x) ) {
x[i] <- x[i] + 5
}
# try to do something that makes x squared, i.e. x == c(1,4,9).
Thirdly, look at ?sum, whereby sum(x) adds up all the elements in x.
the_answer <- sum( (1:3)^2 )
For-loops are so last century.

Resources