gpt4 book ai didi

r - 比较两个 data.frame 并删除具有共同字符的行

转载 作者:行者123 更新时间:2023-12-01 08:05:57 25 4
gpt4 key购买 nike

我有两个 data.frame x1 和 x2。如果在 x1 和 x2 中发现了共同基因,我想从 x2 中删除行

x1 <- chr   start   end         Genes   
1 8401 8410 Mndal,Mnda,Ifi203,Ifi202b
2 8001 8020 Cyb5r1,Adipor1,Klhl12
3 4001 4020 Alyref2,Itln1,Cd244

x2 <- chr start end Genes
1 8861 8868 Olfr1193
1 8405 8420 Mrgprx3-ps,Mrgpra1,Mrgpra2a,Mndal,Mrgpra2b
2 8501 8520 Chia,Chi3l3,Chi3l4
3 4321 4670 Tdpoz4,Tdpoz3,Tdpoz5



x2 <- chr start end Genes
1 8861 8868 Olfr1193
2 8501 8520 Chia,Chi3l3,Chi3l4
3 4321 4670 Tdpoz4,Tdpoz3,Tdpoz5

最佳答案

你可以试试

x2[mapply(function(x,y) !any(x %in% y), 
strsplit(x1$Genes, ','), strsplit(x2$Genes, ',')),]
# chr start end Genes
#2 2 8501 8520 Chia,Chi3l3,Chi3l4
#3 3 4321 4670 Tdpoz4,Tdpoz3,Tdpoz5

或者将 !any(x %in% y) 替换为 length(intersect(x,y))==0

注意:如果“Genes”列是“factor”,请将其转换为“character”,因为 strsplit 不能采用“factor”类。即 strsplit(as.character(x1$Genes, ','))

更新

基于 'x2' 的新数据集,我们可以通过 'chr' 列合并两个数据集,strsplit 'Genes.x', 'Genes .y' 来自输出数据集('xNew'),根据 'Genes.x' 的任何元素在 'Genes.y' 字符串中的出现获取逻辑索引,使用它来子集 'x2' 数据集

 xNew <- merge(x1, x2[,c(1,4)], by='chr')
indx <- mapply(function(x,y) any(x %in% y),
strsplit(xNew$Genes.x, ','), strsplit(xNew$Genes.y, ','))
x2[!indx,]
# chr start end Genes
#1 1 8861 8868 Olfr1193
#3 2 8501 8520 Chia,Chi3l3,Chi3l4
#4 3 4321 4670 Tdpoz4,Tdpoz3,Tdpoz5

关于r - 比较两个 data.frame 并删除具有共同字符的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29082934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com