Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在两个矩阵/数据帧中查找同一行,然后在R中的一个矩阵/数据帧中删除_R - Fatal编程技术网

在两个矩阵/数据帧中查找同一行,然后在R中的一个矩阵/数据帧中删除

在两个矩阵/数据帧中查找同一行,然后在R中的一个矩阵/数据帧中删除,r,R,假设我们有以下矩阵或数据帧dyad_1和dyad_2: dyads_0 <- gtools::permutations(n=16,v=c(1:16), r=2) dyad_1<- NULL for (i in c(1,3:16)){ dyads1 <-NULL dyads1 <- gtools::permutations(n=4,v=c(i,17:19), r=2) dyad_1 <- rbind(dyad_1,dyads1[-c(5,6,8,9,11,12)

假设我们有以下矩阵或数据帧dyad_1和dyad_2:

dyads_0 <- gtools::permutations(n=16,v=c(1:16), r=2)

dyad_1<- NULL

for (i in c(1,3:16)){

dyads1 <-NULL
dyads1 <- gtools::permutations(n=4,v=c(i,17:19), r=2)
dyad_1 <- rbind(dyad_1,dyads1[-c(5,6,8,9,11,12),]) 
}

dyad_1<- rbind(dyads_0,dyad_1) 
dyad_2<- gtools::permutations(n=19,v=c(1:19), r=2)
假设二元数为1

V1 V2
1  2
2  3
3  2
10 5
输出应如下所示:

 V0  V1  V2  V4
 0   1   3  0.2
 1   2   1  0.15 
 0   3   1   0
这只是一个澄清示例,与上述代码不同

如果您能给我您的解决方案,我将不胜感激,因为我已经被卡住了。

anti_-join
()在这里非常有用-它基本上与join相反-根据文档,
anti_-join(x,y)
返回x中的所有行,y中没有匹配项。因此,将每个设置为data.frame并使用dplyr的anti_join,我们可以在几行中完成此操作:

library(dplyr)
dyad_2 <- as.data.frame(dyad_2)
dyad_1 <- as.data.frame(dyad_1)
# filter out the columns that appear in both datasets
dyad_2 <- dplyr::anti_join(dyad_2, dyad_1, by = c("V1", "V2"))

您可以按行粘贴
dyad_1
dyad_2
中的值,并保留未包含的行

val1 <- apply(dyad_1, 1, paste0, collapse = '-')
val2 <- apply(dyad_2, 1, paste0, collapse = '-')
result <- dyad_2[!val2 %in% val1, ]

val1当我尝试执行你的代码时,我得到一个行
dyad的错误_1@Till谢谢你指出这一点。那是个打字错误。已经更正了。谢谢。它能推广到更大的矩阵吗?也就是说,二元_2是一个有4列的矩阵,二元_1是一个有两列的矩阵。所以我们想在二元体2中搜索并删除那些第三和第四元素与二元体相似的行。明白了吗?没问题。这有点复杂-您可能只想在感兴趣的列上反_连接,然后在其他列中合并,例如:dyad_3取决于dyad_1和dyad_2是data.tables。顺便说一下。谢谢,@gabesolomon10,但它产生了一个错误。假设我们有下面的dyad_2$V0感谢@Ronak Shah,这很有效。你能看看我上面最后的评论吗。我要求概括。@Mori您能用示例和相应的预期输出更新您的帖子吗?谢谢,@Ronak Shah,我已经更新了。事实上,我的数据比这个大得多。如果你愿意,我可以把我的实际数据发送给你。
dyad_2
actual是你帖子中的一个矩阵。那么,Ronak Shah现在清楚了吗?
library(dplyr)
dyad_2 <- as.data.frame(dyad_2)
dyad_1 <- as.data.frame(dyad_1)
# filter out the columns that appear in both datasets
dyad_2 <- dplyr::anti_join(dyad_2, dyad_1, by = c("V1", "V2"))
> dyad_2
    V1 V2
1    1 17
2    1 18
3    1 19
4    2 17
5    2 18
...
98  19 14
99  19 15
100 19 16
101 19 17
102 19 18
val1 <- apply(dyad_1, 1, paste0, collapse = '-')
val2 <- apply(dyad_2, 1, paste0, collapse = '-')
result <- dyad_2[!val2 %in% val1, ]
val1 <- apply(dyad_1, 1, paste0, collapse = '-')
val2 <- apply(dyad_2[, colnames(dyad_1)], 1, paste0, collapse = '-')
dyad_2[!val2 %in% val1, ]

#  V0 V1 V2   V4
#2  0  1  3 0.20
#3  1  2  1 0.15
#5  0  3  1 0.00