Generate matrix from uneven vectors, matching presence and absence as 0 or 1

I'm looking to incorporate information from different sized vectors into a matrix. I'd like to list values as either row or column names, and if present in any one of these vectors, will be set to 1. If absent in any one of these vectors, will be set to 0. I can have upwards of 20 vectors, containing a string of upwards of 300 values Apologies if my terminology is incorrect, I'm relatively new to R!

An example of my data:
v1 = "ASV581" "ASV547" "ASV434" "ASV378" "ASV7" "ASV1478" "ASV676" "ASV361" "ASV142" "ASV92" "ASV16" "ASV2"

v2 = "ASV15" "ASV7" "ASV5" "ASV2" "ASV676" "ASV581" "ASV522" "ASV361"

v3 = "ASV1" "ASV7" "ASV3" "ASV15 "ASV2" "ASV38" "ASV28 "ASV22" "ASV5" "ASV346""ASV208" "ASV139" "ASV13" "ASV919" "ASV676"

v4 = "ASV15" "ASV7" "ASV5" "ASV2" "ASV208" "ASV139" "ASV361" "ASV142"

So far I've combined all vectors and generated a unique list:
x <- c(v1, v2, v3, v4)
ASVitems <- unique(x)

But I seem to be having problems generating the matrix and get setting conditions for presence or absence.

Here is an example of what I would like to have, where ASVs are row names:
[v1] [v2] [v3] [v4] ...
ASV2 1 1 1 1
ASV3 0 0 1 0
ASV5 0 1 1 0
ASV7 1 1 1 1
...

Thanks!
A

I think this does what you want.

v1 = c("ASV581", "ASV547", "ASV434", "ASV378", "ASV7", "ASV1478", "ASV676", "ASV361", "ASV142", "ASV92", "ASV16", "ASV2")

v2 = c("ASV15", "ASV7", "ASV5", "ASV2", "ASV676", "ASV581", "ASV522", "ASV361")

v3 = c("ASV1", "ASV7", "ASV3", "ASV15", "ASV2", "ASV38", "ASV28", "ASV22", "ASV5", "ASV346", "ASV208", "ASV139", "ASV13", "ASV919", "ASV676")

v4 = c("ASV15", "ASV7", "ASV5", "ASV2", "ASV208", "ASV139", "ASV361", "ASV142")

x <- c(v1, v2, v3, v4)
ASVitems <- unique(x)
v1Pres <- as.numeric(ASVitems %in% v1)
v2Pres <- as.numeric(ASVitems %in% v2)
v3Pres <- as.numeric(ASVitems %in% v3)
v4Pres <- as.numeric(ASVitems %in% v4)

Mat <- matrix(c(v1Pres, v2Pres, v3Pres,v4Pres), byrow = FALSE, nrow = 25)
dimnames(Mat) <- list(ASVitems, c("v1","v2","v3","v4") )
Mat
#>         v1 v2 v3 v4
#> ASV581   1  1  0  0
#> ASV547   1  0  0  0
#> ASV434   1  0  0  0
#> ASV378   1  0  0  0
#> ASV7     1  1  1  1
#> ASV1478  1  0  0  0
#> ASV676   1  1  1  0
#> ASV361   1  1  0  1
#> ASV142   1  0  0  1
#> ASV92    1  0  0  0
#> ASV16    1  0  0  0
#> ASV2     1  1  1  1
#> ASV15    0  1  1  1
#> ASV5     0  1  1  1
#> ASV522   0  1  0  0
#> ASV1     0  0  1  0
#> ASV3     0  0  1  0
#> ASV38    0  0  1  0
#> ASV28    0  0  1  0
#> ASV22    0  0  1  0
#> ASV346   0  0  1  0
#> ASV208   0  0  1  1
#> ASV139   0  0  1  1
#> ASV13    0  0  1  0
#> ASV919   0  0  1  0

Created on 2024-02-27 with reprex v2.0.2

Wow! Exactly what I need! Thank you very much!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.