Home > Blockchain >  How to compare vectors with different structures
How to compare vectors with different structures

Time:06-25

I have two vectors (fo, fo2) and I would like to compare if the numbers are matching between them (such as with intersect(fo,fo2)).

However, fo and fo2 can't be compared directly. fo is numeric (each element is typed into c() ) while fo2 is read from a string such as "1 3 6 7 8 10 11 13 14 15".

The output of the vectors are produced here for illustration. Any help is greatly appreciated!

# fo is a vector
> fo <- c(1,3,6,7,8,9,10,11)
> fo
[1]   1   3   6   7   8  10  11 

> is.vector(fo)
[1] TRUE

# fo2 is also a vector
> library(stringr)
> fo2 <- str_split("1 3 6 7 8 10 11 13 14 15", " ")
> fo2
[[1]]
 [1] "1"   "3"   "6"   "7"   "8"   "10"  "11"  "13"  "14"  "15"

> is.vector(fo2)
[1] TRUE

> intersect(fo,fo2)
list()

CodePudding user response:

fo2 here is list vector but fo is atomic vector so to get the intersect e.g.

intersect(fo , fo2[[1]])

#> [1] "1"  "3"  "6"  "7"  "8"  "10" "11"

to learn the difference see Vectors

CodePudding user response:

Another option:

fo %in% fo2[[1]]

Output:

[1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE

Check with setdiff:

setdiff(fo, fo2[[1]])

Output:

[1] 9
  • Related