基于数据框中另一个字符向量的向量条件替换
Conditional replacement in vector based on the another character vector in dataframe
我有一个数据框,其中包含名为 "mutation" 的列。它们可以是像 "C > A" 这样的 SNP,像 "+TTTAAG" 这样的插入或像 "-CTTGA" 这样的删除。例如:
**position** **mutation**
1234 C > A
1452 +TTTAAG
2734 -CTTGA
我要R在突变列(“>”、“+”或“-”)中搜索特定字符并分别写入"SNP"、"insertion"或"deletion"数据框中的新列,所以我希望得到以下结果:
**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 列中的每个单元格。你能给我一个解决这个问题的建议吗?
使用 grep
和 ifelse
的解决方案:
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
我有一个数据框,其中包含名为 "mutation" 的列。它们可以是像 "C > A" 这样的 SNP,像 "+TTTAAG" 这样的插入或像 "-CTTGA" 这样的删除。例如:
**position** **mutation**
1234 C > A
1452 +TTTAAG
2734 -CTTGA
我要R在突变列(“>”、“+”或“-”)中搜索特定字符并分别写入"SNP"、"insertion"或"deletion"数据框中的新列,所以我希望得到以下结果:
**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 列中的每个单元格。你能给我一个解决这个问题的建议吗?
使用 grep
和 ifelse
的解决方案:
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