Consider the vector:
use = c(1,1,2,2,5,1,2,1,2,5,1)
I'm trying to replace all the numbers different from 5 to NA before the first number 5 shows up in the sequence:
ifelse(use != 5,NA,1)
.
After that the condition should be
ifelse(use != 5,0,1)
.
The output would be:
after = c(NA,NA,NA,NA,1,0,0,0,0,1,0)
Any tips?
Let’s say that we have to replace all the elements by Value 1, then after replacing each value in the given vector by 1 are vector should become like the figure below :- A naive way of doing this is to traverse the entire vector and replace each element with the given value.
Using std::replace_if The best option to conditionally replace values in a vector in C++ is using the std::replace_if function. It assigns a new value to all the elements in the specified range for which the provided predicate holds true.
Within the replace function, we have to specify the name of our vector object (i.e. my_vec, a logical condition (i.e. my_vec == 1), and the value we want to insert (i.e. 999): The output of the previous R syntax is exactly the same as in Example 1.
We can directly enter the new or updated value using the ‘=’ operator to assign the value to that location. For instance, the vector element at index 4 is modified as -1 in this case. 2. Using ‘ [ ]’ operator
You should try:
`is.na<-`(match(use, 5, 0), seq(match(5, use) - 1))
[1] NA NA NA NA 1 0 0 0 0 1 0
Weird subsetting:
c(NA[!cumsum(use == 5)], +(use[!!cumsum(use == 5)] == 5))
#[1] NA NA NA NA 1 0 0 0 0 1 0
We can use match
replace(use, seq_len(match(5, use) - 1), NA)
#[1] NA NA NA NA 5 1 2 1 2 5 1
Or as @M-- commented, this can be changed to binary with
+(replace(use, seq_len(match(5, use) - 1), NA)==5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With