【问题标题】:Convert similar names to figures将相似名称转换为数字
【发布时间】:2018-03-06 23:38:25
【问题描述】:

我有不同的基因型,例如他们的血统有很多父母

genotypes parents
G1        mac cemolt giza
G2        mac miser
G3        misr cemolt mac NE10

我有很多基因型,我想制作一个矩阵,其中包括每两个基因型之间的共同父母,所以它应该看起来像

   G1 G2 G3
G1 0   1  2
G2        2

我该怎么做?

【问题讨论】:

    标签: r excel statistics


    【解决方案1】:

    这是一个使用可重现代码和嵌套 sapplys 的 intersect 函数的解决方案。

    genotypes <- c("G1", "G2", "G3")
    parents <- list(c("mac", "cemolt", "giza"), c("mac", "miser"),
                 c("miser", "cemolt", "mac", "NE10"))
    
    comparisons <- sapply(parents, function(x) 
        sapply(parents, function(y) length(intersect(x,y))))
    rownames(comparisons) <- genotypes
    colnames(comparisons) <- genotypes
    
    as.dist(comparisons)
    

    【讨论】:

      【解决方案2】:

      1) 生成数据框:

      df <- data.frame(genotypes = c("G1", "G2", "G3"),
                             parents = c("mac cemolt giza",
                                         "mac miser",
                                         "miser cemolt mac NE10"),
                             stringsAsFactors = FALSE)
      

      2) 编写函数来查找基因型字符串中的共同父母。

      假设: 在 parents 列中,每个 parent 用空格分隔。如果将基因型与其自身进行比较,则返回 0 个共同父母(基于您的预期结果表)。

      commonParents <- function(vector1, vector2) {
          lapply(1:length(vector1), function(x) {
              if(vector1[x] == vector2[x]) {
                  return(0)
              } else {
                  parents <- unlist(strsplit(vector1[x], split = " "))
                  sum(sapply(parents, function(y) grepl(y, vector2[x], ignore.case = TRUE)))   
              }
          })
      }
      

      3) 使用outer 创建值矩阵:

      outer(df$parents, df$parents, FUN = "commonParents")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-01
        • 1970-01-01
        • 2012-08-07
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 2020-11-07
        相关资源
        最近更新 更多