I want to create a matrix and assign 1s based on matching the rownames
of the matrix to the character vector.
## Here is the small example matrix
x <- as.character(c("rm78", "mn05", "hg78"))
y <- as.character(c("JU67", "EX56", "abcd", "rm78", "xyh56", "def", "terr6572"))
z <- as.character(c("abcd", "rh990", "mn05", "rm78", "xyh56", "efdg", "bett72"))
common <- Reduce(union, list(x,y,z))
dat.names <- c("x", "y", "z")
mat0 <- matrix(0, nrow = length(common), ncol = length(dat.names))
colnames(mat0) <- dat.names
rownames(mat0) <- common
mat0
If the character vectors x
, y
, and z
matches the rownames
of the matrix mat0
then assign 1 to the corresponding value in the matrix.
I am doing this individually for each vector and adding values to the matrix. I have a list of more than 12 such vectors and doing this way would be redundant. I think there may be a much efficient way of doing this.
for(i in rownames(mat0)[rownames(mat0) %in% x])
{
# first column
mat0[i , 1] <- 1
}
for(i in rownames(mat0)[rownames(mat0) %in% y])
{
# second column
mat0[i , 2] <- 1
}
for(i in rownames(mat0)[rownames(mat0) %in% z])
{
# third column
mat0[i , 3] <- 1
}
Yes, you don't need multiple loops. In fact, you don't need any:
mat0[] <- do.call(cbind, lapply(list(x, y, z), function(i) +(rownames(mat0) %in% i)))
mat0
#> x y z
#> rm78 1 1 1
#> mn05 1 0 1
#> hg78 1 0 0
#> JU67 0 1 0
#> EX56 0 1 0
#> abcd 0 1 1
#> xyh56 0 1 1
#> def 0 1 0
#> terr6572 0 1 0
#> rh990 0 0 1
#> efdg 0 0 1
#> bett72 0 0 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.