1

I've made this simple code to test something that isn't working.

funcion=function(x,p){
 for(i in 1:p){
  return(x+i)
 }
}
funcion(5,5)

This returns the value 6, and not 6,7,8,9,10 which is what I would've expected and what I'm looking for. Can someone explain why this works this way and how can I make it so that I get what I want?

Thank you

1 Answer 1

2

We need to collect the output in an object and then return

f1 <- function(x, p) {
        # // create an object to store the output from each iteration
        out <- numeric(p)
        for(i in seq_len(p)) {
            out[i] <- x + i # // assign the output based on the index
         }
        return(out)
 }

f1(5, 5)
#[1]  6  7  8  9 10

In R, this can be executed without a for loop i.e.

5 + seq_len(5)
#[1]  6  7  8  9 10

The issue is that return inside a function returns only once. So, it gets executed the first time with x + 1 and it return that output instead of the full output

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much! Specifying the length of vectors makes it faster to execute right?
@Python_begginer23 It will make it faster. Most of the R functions are vectorized. So, you don't need a for loop.
This is just an example. In the project that I'm actually doing I think I'd rather have a for loop.
@Python_begginer23 Good to know about the reasoning. Thank you
@Python_begginer23 in addition, you may also use lapply/sapply if you don't want to create output objects. i.e. sapply(seq_len(5), +, 5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.