【发布时间】:2020-07-25 16:10:14
【问题描述】:
我想创建一个矩阵并根据矩阵的rownames与字符向量的匹配来分配1。
## 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
如果字符向量x、y 和z 匹配矩阵rownames 的mat0,则将1 分配给矩阵中的对应值。
我为每个向量单独执行此操作并向矩阵添加值。我有一个超过 12 个这样的向量的列表,这样做是多余的。我认为可能有一种非常有效的方法。
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
}
【问题讨论】: