【问题标题】:Assigning values to the matrix by matching column names of matrix and character vectors通过匹配矩阵和字符向量的列名来为矩阵赋值
【发布时间】: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

如果字符向量xyz 匹配矩阵rownamesmat0,则将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 
}

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    是的,您不需要多个循环。事实上,你不需要任何东西:

    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
    

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多