1

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?

4

3 回答 3

1

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)
于 2013-07-22T16:28:41.170 回答
1
values[values %% 2 == 1] <- NA
于 2013-07-22T16:38:19.640 回答
1

You don't need to use tricks and sum anything, this will suffice:

values = ifelse(values %% 2 == 0, values/2, NA)
于 2013-07-22T20:53:49.843 回答