-2

I have am trying to loop over a numeric vector. How do I do this? Typically in a for loop one begins the loop with for(i in 1:z). However, I want something like for(i in vector). For example, see the below:

x <- c(839898, 3, 9)
for (i in x) { print(i) }

# Desired output
839898
3
9

In this instance, I do not want to vectorize this as I am trying to learn how to accomplish this with a for loop.

While this post is similar to many others, in almost all of the others I have seen only vectorized solutions because someone was trying to accomplish a task with minimal run time rather than learn how the loops work.

Sumedh
  • 4,835
  • 2
  • 17
  • 32
socialscientist
  • 3,759
  • 5
  • 23
  • 58
  • 3
    Your example works, I have no idea what else you want. – catastrophic-failure Jul 23 '16 at 23:49
  • 2
    AFAIK using an `apply` function is not vectorized. I suspect that in any solution below R will use a loop internally at some point (it will for `apply`). – Tim Biegeleisen Jul 23 '16 at 23:50
  • 2
    It worked for me too. Is there a reason why you don't want to work in standard R principles and vectorize things? Loops are generally not good practice in R. – Vedda Jul 23 '16 at 23:51
  • It was a typo. @Amstell, I was trying to learn and not use it for a substantive application. I also consider `apply` vectorized for this reason: http://stackoverflow.com/questions/28983292/is-the-apply-family-really-not-vectorized Also, whoever went through my old posts and down voted is fairly pathetic - but alas, such is the internet (and the battle over reputation on an online forum). – socialscientist Jul 24 '16 at 03:22

2 Answers2

2

I believe you are making a typo above, and you want to print i instead of print x. Here is the execution in RStudio.

Screenshot of Code Execution in RStudio

puzzled123
  • 312
  • 1
  • 2
  • 12
1

You need this:

for (i in seq_along(x)) {
    print(x[i])
}

You are printing x directly which is defined the global environment. You want to print the ith element of x in the for loop

Sumedh
  • 4,835
  • 2
  • 17
  • 32