 # A doubt with vectors - beginner level

Hello,

I'm beginner in R Studio and I've a test about vectors and their ordenation next week, but I still have some doubts. I don't know if here is the right place to send my question.

Well, bellow I send the code:

vetor_dados <- c(78, 32, 2, 65, 27)

``````  x <- vetor_dados
cont1 <- 0
cont2 <- 0

for(n in x){
cat(cont1, " ")
if((n %% 2) != 0){   # (a %% b)
cont1 <- cont1 + 1
}else{
cont2 <- cont2 + 1
}

}
``````

Can anybody help me with this code and its result? I would like an explanation, not only an answer. In my test we can't use R Studio to run codes...

Thanks!

Welcome to the forum, PPlayer.

Note:
While you've provided code, you've given very little information about (a) the specific question you need help with, (b) what it is you don't understand about it, and/or (c) how the piece of code you've provided relates to that question. For future reference, it is always useful to try and clearly outline these aspects in questions posted online in order to ensure that you and the rest of the community get the most helpful/useful responses. The best I can do at this stage is to guess that your question is somewhere along the lines of "Here is some code. What on earth is going on here?" If that is indeed the case, you can see my take below. If not, it may be good if you edited the question and provided more clarity.

Interpretation:

• The code seems to be intended to count the number of odd and even numbers (i.e. numbers that are/aren't divisible by 2) in `vetor_dados`:
• a `for` loop is used to iterate over the `x` vector (which is originally set equal to `vector_dados`
• in each iteration an `if`/`else` statement pair is used to determine if the number in question is/isn't divisible by 2.
• if the number isn't divisible my 2 (i.e. `n %% 2) != 0`), then `cont1` should be incremented by a value of 1, otherwise `cont2` should be incremented by a value of 1 (`cont1` and `cont2` are effectively initialized as placeholder vectors with startin values of 0 at the beginning of the code chunk)
• at the end of the loop, the values of `cont1` and `cont2` respectively tell us that there are 2 uneven and 3 even numbers in `x`
• note that you could have obtained the same insights with far more efficient code. One way of seeing this is to run the single line of code `table(x %% 2)` which reveals substantively the same information.

Hope that helps!

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.