Reputation: 442
I'm trying to find a way to insert NA values into a vector / matrix in R. I've used some manipulation tricks like:
values = *expression* #assume values is a populated vector
values = (values %% 2 == 0)(values/2) + (values%%2 == 1)*(3*values + 1)
So, this conditionally manipulates entries of the vector based on their values, but I'm not sure how to do this type of method while inserting NA values since something like values = (values %% 2 == 0)*(values) + (values%%2 == 1)*(NA)
will produce nothing but NA's for the whole vector.
I've found that I can do something like the following:
for(i in 1:length(values))
{
if(values[i] %% 2 == 1){values[i] = NA}
}
But I was hopeful for something a little more concise, like the previous example. Any thoughts?
Upvotes: 1
Views: 962
Reputation: 49448
You don't need to use tricks and sum anything, this will suffice:
values = ifelse(values %% 2 == 0, values/2, NA)
Upvotes: 1
Reputation: 4414
like this ?
v = (values %% 2 == 0)*(values/2) + ifelse(values%%2 == 1, NA, 0)
Actually it is safer to write:
v = ifelse(values %% 2 ==0, values/2, 0) + ifelse(values%%2 == 1, NA, 0)
Upvotes: 1