pset[[1]]="000100" "100110" "001000" "100000" "100001" "100010"
true="000110"
I want to match only 1's from true to pset[[1]]. For example: true has 1 at digit 4 and 5 and pset[[1]] has second element which has 1 at digit 4 and 5.
So I should get answer as 1.
Can anyone help me out with this. I know match command in R but it matches all digits. However, I am only interested in 1's
CodePudding user response:
These are bitwise operations dealing with binary numbers.\
You could do:
sum(sapply(pset, function(x) rawToChar(charToRaw(x)&charToRaw(true)))==true)
[1] 1
CodePudding user response:
This is quite convoluted and perhaps suboptimal, but here you go:
- Turn your digit strings into arrays of booleans
to_bool <- function(s) strsplit(s, "")[[1]] == "1"
true_bool = to_bool(true)
pset_bool = lapply(pset, to_bool)
- Your condition is satisfied when the AND of pset_bool and true_bool (which represents the digits that are true in both strings) is identical to true_bool (meaning, all the digits that are true in true_bool were not false in pset_bool, or the AND would have returned false)
sapply(pset_bool, function(b) all((b & true_bool) == true_bool))
[1] FALSE TRUE FALSE FALSE FALSE FALSE
CodePudding user response:
We could subtract each digit after strsplit
and check if any is less than zero.
sapply(pset, \(x) {
!any(do.call(`-`, lapply(strsplit(cbind(true, x), ''), as.numeric)) < 0)
}, USE.NAMES=FALSE) |> which()
# [1] 1
Data:
pset <- c("000100", "100110", "001000", "100000", "100001", "100010")
true <- "000110"