[英]R which rows in a dataframe exist in another dataframe
我有兩個數據框 A 和 B:
x y
1 0.0 0.0000000
2 0.5 0.8000000
3 -0.5 0.8000000
4 -1.0 0.0000000
5 -0.5 -0.8000000
6 0.5 -0.8000000
7 1.0 0.0000000
8 1.5 0.8000000
x y
1 -1.0 0.0000000
2 0.5 -0.8000000
3 3.0 0.0000000
我想只提取 B 中存在的 A 中的行索引,以便最終結果為:
c(4,6)
我該怎么做呢?
interaction
可用於在多個列上使用%in%
。
which(interaction(A) %in% interaction(B))
#[1] 4 6
數據
A <- read.table(header=TRUE, text=" x y
1 0.0 0.0000000
2 0.5 0.8000000
3 -0.5 0.8000000
4 -1.0 0.0000000
5 -0.5 -0.8000000
6 0.5 -0.8000000
7 1.0 0.0000000
8 1.5 0.8000000")
B <- read.table(header=TRUE, text=" x y
1 -1.0 0.0000000
2 0.5 -0.8000000
3 3.0 0.0000000")
向 A 添加另一列,這只是一個序列,然后合並
> A$c=1:nrow(A)
> merge(A,B)$c
[1] 4 6
一種可能的方法是計算 TRUE 出現兩次的次數。 如果列變得更寬,您可以映射它們。
which(`+`(df1$x %in% df2$x, df1$y %in% df2$y) == 2)
4 6
使用plyr
中的join.keys
函數:
library(plyr)
with(join.keys(A, B), which(x %in% y))
輸出:
[1] 4 6
library(data.table)
setDT(A)
setDT(B)
A[fintersect(A, B), on = names(A), which = TRUE]
# [1] 4 6
library(dplyr)
A |>
mutate(row = row_number()) |>
inner_join(B, by = names(A)) |>
pull(row)
# [1] 4 6
數據
A = data.frame(
x = c(0, 0.5, -0.5, -1, -0.5, 0.5, 1, 1.5),
y = c(0, 0.8, 0.8, 0, -0.8, -0.8, 0, 0.8))
B = data.frame(
x = c(-1, 0.5, 3), y = c(0, -0.8, 0)
)
使用outer
which(rowSums(outer(1:nrow(A), 1:nrow(B), Vectorize(\(i, j) all(A[i, ] == B[j, ])))) == 1)
# [1] 4 6
或for
循環
r <- c()
for (j in seq_len(nrow(B))) {
for (i in seq_len(nrow(A))) {
if (all(A[i, ] == B[j, ])) r <- c(r, i)
}
}
r
# [1] 4 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.