Problems with NA in R

Asked

Viewed 41 times

1

Good evening everyone, I want to write a function in R that checks the even elements and display them on screen later. From that I wrote the following code:

pares <- function(v){
    for(i in v){
        if ((v[i]%%2)==0){
        b[i]<-c(v[i])
    }
}
print(b)

}
pares(a)

with this I received the following reply from the compiler: [1] 0 2 NA 4 NA 6 NA 8 NA 10 I don’t know what’s causing it, could someone help me remove these "NA"? Thank you very much in advance.

1 answer

2


You are confusing the code to loop with a counter and an array loop. When you do the for i in v, each time the loop rotates it rotates it puts the value of the next value of v in i.

The correct form would be:

pares <- function(v){
    for(i in v){
        if ((i%%2)==0){
        b <- append(b, i)
    }
}
print(b)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.