Reputation: 325
How can I remove only AN element from a vector in R? For example,
x = c(1, 2, 0, 3, 1, 4, 2, 0)
I want to delete only one of the zeros, randomly. Then
x = c(1, 2, 0, 3, 1, 4, 2)
or
x = c(1, 2, 3, 1, 4, 2, 0)
Upvotes: 3
Views: 437
Reputation: 99331
To randomly choose which zero gets removed, you can use
x[-sample(which(x == 0), 1)]
Obviously the above will only work if there is at least one zero in x
. As a safeguard, you can use an if()
statement.
if(length(w <- which(x == 0))) x[-sample(w, 1)] else x
# [1] 1 2 0 3 1 4 2
if(length(w <- which(x == 0))) x[-sample(w, 1)] else x
# [1] 1 2 3 1 4 2 0
Searching for 11
, where there are none, we get the entire vector x
back.
if(length(w <- which(x == 11))) x[-sample(w, 1)] else x
# [1] 1 2 0 3 1 4 2 0
Upvotes: 3