Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the conditions to replace elements in a vector

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?

like image 937
L. Rattis Avatar asked Jan 14 '20 18:01

L. Rattis


People also ask

How to replace all the elements in a vector by 1?

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.

How do you conditionally replace a vector in C++?

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.

How do you replace a vector with a value in R?

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.

How to change the value of a vector element in Excel?

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


3 Answers

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
like image 81
KU99 Avatar answered Sep 23 '22 06:09

KU99


Weird subsetting:

c(NA[!cumsum(use == 5)], +(use[!!cumsum(use == 5)] == 5))
#[1] NA NA NA NA  1  0  0  0  0  1  0
like image 24
utubun Avatar answered Sep 25 '22 06:09

utubun


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)
like image 24
akrun Avatar answered Sep 24 '22 06:09

akrun