[英]Subset data frame when two columns have specific different values
I have a data frame with this structure:我有一个具有这种结构的数据框:
ID Chromosome.EU Position.EU Chromosome.AM Position.AM
AX-875 chr02 50241802 chr02 1773016
AX-964 chr02 51189882 chr05 2720414
AX-873 chr04 51371415 chr04 2902066
AX-962 chr06 51442510 chr02 2973445
AX-872 chr05 51531135 chr02 3067694
AX-877 chr02 51806507 chr05 3357612
AX-869 chr05 51816808 chr05 3367924
I want to get a subset including only the IDs with different chromosome locations, but only according to the couple chr02-chr05 , ie:我想得到一个子集,仅包括具有不同染色体位置的 ID,但仅根据这对chr02-chr05 ,即:
ID Chromosome.EU Position.EU Chromosome.AM Position.AM
AX-964 chr02 51189882 chr05 2720414
AX-872 chr05 51531135 chr02 3067694
AX-877 chr02 51806507 chr05 3357612
I have written a conditional sentence which I thing fulfills what I am looking for:我写了一个条件句,我的东西满足了我正在寻找的东西:
df[(df$Chromosome.EU=="chr02" & df$Chromosome.AM=="chr05") | (df$Chromosome.EU=="chr05" & df$Chromosome.AM=="chr02"),]
However, it seems too long to me, I would like to know if a more concise structure is possible.但是,对我来说似乎太长了,我想知道是否可以使用更简洁的结构。 Thanks in advance!
提前致谢!
A "tidyverse" solution. “tidyverse”解决方案。 I'm not sure whether this counts as "more concise", but I think it's somewhat readable.
我不确定这是否算作“更简洁”,但我认为它有点可读性。 You can create a new column by sorting and pasting the chromosome pairs to create, for example, "chr02chr05", and then filter on that.
您可以通过对染色体对进行排序和粘贴来创建一个新列,例如“chr02chr05”,然后对其进行过滤。
library(dplyr)
library(purrr)
df %>%
mutate(ChromPair = map2(Chromosome.EU, Chromosome.AM, ~
paste0(sort(c(.x, .y)), collapse = ""))) %>%
filter(ChromPair == "chr02chr05")
Result:结果:
ID Chromosome.EU Position.EU Chromosome.AM Position.AM ChromPair
1 AX-964 chr02 51189882 chr05 2720414 chr02chr05
2 AX-872 chr05 51531135 chr02 3067694 chr02chr05
3 AX-877 chr02 51806507 chr05 3357612 chr02chr05
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.