How to construct this binary variable in R? -


the aim check if value @ index 1 , make previous 6 entries 1.

x <- c(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1)  ## required output  y <- c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1)  ## attempt  for(j in seq_along(x)){ if(x[j] == 1){    for(i in (j-6):j)    x[i] = 1    }} 

could solve or better approach ?

thanks.

a vectorized solution using filter:

as.integer( #turn logical value numbers   as.logical( #coerce logical --> 0 becomes false, else true    rev( #reverse order     filter( #linear filtering       c(rep(0, 6), #pad zeros in beginning avoid nas         rev(x)), #revers order of input vector           c(rep(1, 7)), sides=1 #y_i = x_i * 1 + x_(i-1) * 1 +...+ x_(i-6) * 1    )[-(1:6)]))) #remove na values  #[1] 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -