Saurabh
Saurabh

Reputation: 1626

R Lookback few days and assign new value if old value exists

I have two timeseries vectors as follows -

a <- c(1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0)
b <- c(1, 0, 1, 0)

I want to look back 7 days and replace only 1's in vectors a and b with 2. It is important to check if there were any values 7 days before replacing.

The expected result is -

a = c(1, 0, 0, 0, 1, 0, 2, 1, 1, 0, 2, 0)
b = c(1, 0, 1, 0) - Since no value existed 7 days ago, nothing changes here.

Thanks!

Upvotes: 1

Views: 48

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102309

A base R option by defining an user function f

f <- function(v) replace(v, (ind <- which(v == 1) + 6)[ind <= length(v)], 2)

such that

> f(a)
 [1] 1 0 0 0 1 0 2 1 1 0 2 0

> f(b)
[1] 1 0 1 0

Upvotes: 1

akrun
akrun

Reputation: 887531

We can create a condition with lag

library(dplyr)
f1 <- function(vec) replace(vec, lag(vec, 6) == 1, 2)

-output

f1(a)
#[1] 1 0 0 0 1 0 2 1 1 0 2 0
f1(b)
#[1] 1 0 1 0

Upvotes: 2

Related Questions