【问题标题】:Conditional replacement in vector based on the another character vector in dataframe基于数据帧中另一个字符向量的向量条件替换
【发布时间】:2017-12-22 17:30:52
【问题描述】:

我有一个名为“突变”的列的数据框。它们可以是像“C > A”这样的SNP,像“+TTTAAG”这样的插入或像“-CTTGA”这样的删除。例如:

**position** **mutation**
1234           C > A
1452           +TTTAAG
2734           -CTTGA

我希望 R 在突变列(“>”、“+”或“-”)中搜索特定字符,并将“SNP”、“插入”或“删除”分别写入数据帧的新列中,所以我会得到以下结果:

**position** **mutation**  **mutation_type**
1234           C > A             SNP
1452           +TTTAAG         insertion
2734           -CTTGA           deletion

我尝试做以下事情:

mutation_type <- rep(NA, length(df$position)))
df$mutation_type <- mutation_type #creating a new column with NAs

尝试:

while(grep(pattern = "-", df$mutation)){
  df$mutation_type <- "deletion"
}

只需覆盖 mutation_type 列中的每个单元格。请给我一个建议如何解决这个问题,好吗?

【问题讨论】:

    标签: r dataframe vector conditional character


    【解决方案1】:

    使用grepifelse 的解决方案:

    genotype <- data.frame(position = 1:3,
                           mutation = c("C > A", "+TGCA", "-ACGT"))
    genotype$mutation_type <- 
        ifelse(grepl("\\+", genotype$mutation), "Insertion", 
               ifelse(grepl("\\-", genotype$mutation), "Deletion", "SNP"))
    
      position mutation mutation_type
    1        1    C > A           SNP
    2        2    +TGCA     Insertion
    3        3    -ACGT      Deletion
    

    【讨论】:

    • @makkreker 如果它有助于解决您的问题,您可以接受我的回答
    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多