Reputation: 954
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
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
Reputation: 102700
You can try
> +!!replace(a,c(1,3,5),0)
[1] 0 1 0 1 0 1 1 1
Upvotes: 1
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