简体   繁体   中英

Set specific vector elements to NA in R

I am trying to solve an excercise for my R online course. We have a vector B:

B<-c(seq(10,75,by=1))

And I want to set all the elements, that are divisible by 5 (with no remainder, eg 5, 10, 15) to NA. The vector would then look like (NA, 11, 12, 13, 14, NA, ...,). My idea is to use the modulo operator %% and the replace function:

replace((B%/%5==0),B,NA)

When I do this, the vector return the following output:

[1]  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE    NA    NA    NA    
NA
[14]    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    
NA
[27]    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    
NA
[40]    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    
NA
[53]    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    
NA
[66]    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA

Can anyone suggest a solution to the problem?

您可以使用此:

B[ B %% 5 == 0 ] = NA

Here's another approach using an ifelse() statement:

B <- ifelse(B %% 5 == 0, NA, B)

These ifelse() statements can become linked together in powerful ways to apply multiple conditions to the same vector in one go!

For example, if we wanted to transform all of the even numbers within our B vector to NAs too then we could do this:

B <- ifelse(B %% 5 == 0, NA, ifelse(B %% 2 == 0, NA, B))

More information about the ifelse() function can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM