user3342322
user3342322

Reputation: 11

Unexpected result in R for loop

I don't know why this isn't giving me the desired results.

Here is my vector:

flowers = c("Flower", "Flower", "Vegatative", "Vegatative", "Dead")

Here is my for loop:

   Na = 0
for (i in 1:length(flowers)){
  if (i != "Dead"){
    Na = Na + 1
  }
}
Na

Obviously Na should equal 4, but it gives me a result of 5. When I print the flower's status it prints all 5. I don't want it to read the last one. What's my problem?

Thank you.

Upvotes: 1

Views: 126

Answers (2)

Ari
Ari

Reputation: 1982

The bug in your code is this line:

if (i != "Dead"){

To understand why, it would be best to print out the values of i in the loop:

for (i in 1:length(flowers)){
  print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

That is, you are iterating over numbers (indices of a vector), but not actually selecting the value from the vector when you do the test. To access the values, use flowers[i]:

for (i in 1:length(flowers)){
  print(flowers[i])
}
[1] "Flower"
[1] "Flower"
[1] "Vegatative"
[1] "Vegatative"
[1] "Dead"

And so, the answer to your original question is this:

Na = 0
for (i in 1:length(flowers)){
  if (flowers[i] != "Dead"){
    Na = Na + 1
  }
}
Na
[4]

R offers a lot of facilities for doing computations like this without a loop - it's called vectorization. A good article on it is John Cook's 5 Kinds of Subscripts in R. For example, you could get the same result like this:

length(flowers[flowers != "Dead"])
[1] 4  

Upvotes: 0

josliber
josliber

Reputation: 44340

You seem to be trying to count the number of values in flowers that are not equal to "Dead". In R, the way to do this would be:

sum(flowers != "Dead")
# [1] 4

Upvotes: 4

Related Questions