Home > Net >  Matching digit 1
Matching digit 1

Time:09-29

pset[[1]]="000100" "100110" "101101" "101111" "100001" "100010"

true="100110"

How to go about if I want to match 1's from true to each vector in pset. So, it is matching first , fourth and fifth position of true to all 6 vectors in pset and returns as the answer of matching 1's only as:

1 3 2 3 1 2 i.e.

"100110" & "000100" returns 1

"100110" & "100110" returns 3

"100110" & "101101" returns 2

"100110" & "101111" returns 3

"100110" & "100001" returns 1

"100110" & "100010" returns 2

I know about the match function in R but that would match both 0 and 1 but I only want to match 1 from true to pset vectors and here it depends on the position they are at.

Any help would be greatly appreciated.

I know it might require to convert to boolean but I am still struggling.

CodePudding user response:

One possible way to solve your problem:

x = c("000100", "100110", "101101", "101111", "100001", "100010")

ix  = seq_len(nchar(true))
pos = which(strsplit(true, "")[[1]]=="1")
Reduce(` `, lapply(Map(substr, list(x), ix, ix)[pos], `==`, "1"))

[1] 1 3 2 3 1 2

CodePudding user response:

You can use str_split and which:

f <- function(true, x){
  w1 <- which(str_split(true, "")[[1]] == 1)
  w2 <- sapply(str_split(x, ""), \(x) which(x == 1))
  sapply(w2, \(x) length(intersect(w1, x)))
}

f(true, x)
[1] 1 3 2 3 1 2

Note that \ is a shortcut for function.

  •  Tags:  
  • r
  • Related