Reputation: 824
Suppose I got string_a <- c('1', '3', '4', '9' ,'8')
and I randomly picked two elements from string_a
using the sample()
function. Assume that I got 3
and 8
as a result.
My question is, how can I obtain their indices(position) of 3
and 8
in string_a
and represent them in this form: 01001
, where 1 represents the index of the randomly selected number and 0 represents unselected indices.
More examples:
if 1
and 3
are randomly selected, the binary representation would be 11000
if 9
and 8
are randomly selected, the binary representation would be 00011
and so on...
Upvotes: 3
Views: 58
Reputation: 8413
# assume x to be
x = c('3','9')
paste0(as.numeric(match(string_a, x,nomatch = 0)>0), collapse = "")
Upvotes: 2
Reputation: 887841
We can use %in%
to get a logical vector and then coerce to binary with as.integer
, paste it together
paste(as.integer(string_a %in% sample(string_a, 2)), collapse="")
#[1] "01010"
Upvotes: 3