How can one create a logical vector that has TRUE for the first matching condition and FALSE otherwise?
v = rep(1:4, 3)
v == 3
#[1] FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE
==
gives TRUE for all values that equals 3, but I want only the first one to be TRUE:
#[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
I came up with potential solutions but it always uses the index and then construct the logical vector, and I was wondering if there were simpler one.
tabulate(match(3, v), nbins = length(v))
#[1] 0 0 1 0 0 0 0 0 0 0 0 0
seq_along(v) == min(which(v == 3))
#[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
CodePudding user response:
We may use
v==3&!duplicated(v)
[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Or
seq_along(v)==match(3,v)
[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
CodePudding user response:
In negated vector replace
ing which.max
of comparison with TRUE
.
replace(!v, which.max(v == 3), TRUE)
# [1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Or modulo combined with cumsum
s.
cumsum(cumsum(v %% 3 == 0)) == 1
# [1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE