user11916948
user11916948

Reputation: 954

Change values of a vector to 0 and 1

From a vector I would like to make some values 0 and some values 1. It doesnt work, why?

  a <- c(1,34,5,3,6,67,3,2)


a[c(1,3,5)] <- 0 # works
a[!c(1,3,5)] <- 1 # doesnt work

Should look like

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

Upvotes: 0

Views: 51

Answers (3)

akrun
akrun

Reputation: 887881

We can create the logical index with %in%

a[!seq_along(a) %in% c(1, 3, 5)] <- 1
a
#[1] 0 1 0 1 0 1 1 1

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102700

You can try

> +!!replace(a,c(1,3,5),0)
[1] 0 1 0 1 0 1 1 1

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389265

! is for logical values. Try -

a[-c(1,3,5)] <- 1
a
#[1] 0 1 0 1 0 1 1 1

Upvotes: 3

Related Questions