0

I would like to create a numeric vector with the results of a loop such as

> for (i in 1:5) print(i+1)
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

It seems strange that the same expression without 'print' returns nothing

> for (i in 1:5) i+1
>

Does anyone have an explanation/solution?

4
  • What numeric vector are you attempting to create? Commented Nov 9, 2012 at 1:10
  • i+1 is just for illustrative purposes. I have a more complex function that returns numbers, and I want the results to come in a vector, as in test <- numeric(8); for(i in 1:8){test[i] <- myfunction(i)} Commented Nov 9, 2012 at 1:18
  • Ok, I've added a sapply example to my answer. It pays to have a reproducible example of your problem. As your question stands it appears very basic, and we SO users would have to assume that you weren't asking a very basic question. Commented Nov 9, 2012 at 1:25
  • 1
    @dmvianna - please de-accept my answer and move it to mnel. My hastily added answer is not really good practice and i'd hate to encourage future readers to use it! Commented Nov 9, 2012 at 1:34

2 Answers 2

6

This is standard behaiviour -- when you say you want to create a numeric vector, print will not do that

The expression in a for loop is an argument to the primitive function for

From ?`for` in the value section

for, while and repeat return NULL invisibly. for sets var to the last used element of seq, or to NULL if it was of length zero.

print prints the results to the console.

for(i in 1:5) i + 1

merely calculates i + 1 for each iteration and returns nothing

If you want to assign something then assign it using <-, or less advisably assign


You can avoid an explicit loops by using sapply. This (should) avoid any pitfalls of growing vectors

results <- sapply(1:5, function(i) { i + 1})
Sign up to request clarification or add additional context in comments.

Comments

1

Now frankly, there must be a better solution than this

loopee <- function(x){
  res <- vector(mode = "numeric", length(x))
  for (i in 1:x) {res[i] <- i+1}
  return(res)}

> loopee(5)
[1] 2 3 4 5 6

1 Comment

See my answer. Yes there is.

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.