letter
letter

Reputation: 9

Create vector = (0 1 1 0 0 0 1 1 1 1)?

How can I create the following vector?

vec = (0 1 1 0 0 0 1 1 1 1)

I already tried rep(0:1,times=1:4) which works with numbers other than 0 but does not here...

Upvotes: -2

Views: 893

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

Without rep but cumsum + sequence

> 1 - bitwAnd(1, cumsum(sequence(1:4) == 1))
 [1] 0 1 1 0 0 0 1 1 1 1

or

> 1 - cumsum(sequence(1:4) == 1) %% 2
 [1] 0 1 1 0 0 0 1 1 1 1

Upvotes: 0

Spacedman
Spacedman

Reputation: 94277

Here's a generic solution:

> increp=function(n){rep(0:(n-1), times=1:n) %% 2}
> increp(4)
 [1] 0 1 1 0 0 0 1 1 1 1
> increp(3)
[1] 0 1 1 0 0 0
> increp(2)
[1] 0 1 1
> increp(6)
 [1] 0 1 1 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1

It generates 0,1,1,2,2,2,3,3,3 up to the required length and then just converts to 0/1 based on even or odd.

Upvotes: 4

Heroka
Heroka

Reputation: 13149

For rep, 'times' and 'x' need to have the same length (unless the length of 'times' equals 1). Therefore, you need to make a vector 'x' with length 4 in this case.

> rep(rep(0:1,2),times=1:4)
 [1] 0 1 1 0 0 0 1 1 1 1

Upvotes: 4

Related Questions