Search code examples
rvectorsequence

How to build a vector where every n of 0 is 1 with operator %%?


The code here below

1:nrow(mtcars) %% 4

provides the sequence

1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0

What should I do to get the path?

0 0 0 1 0 0 0 1 0 0 0 1

Solution

  • You could simply wrap it in parenthesis and add an +:

    +(1:nrow(mtcars) %% 4 == 0)
    

    The parentheses - (1:nrow(mtcars) %% 4 == 0) - creates a boolean TRUE/FALSE vector, the + converts those values to 0 or 1.

    Output

    [1] 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1