有没有一种方法可以基于R中另一个数据帧中的共享值构建成对的数据帧?

时间:2020-07-24 01:52:54

标签: r data-wrangling

例如DF1是:

Id1 Id2 
1     10
2     10
3     7
4     7
5     10

想要DF2:

Id1 Id2
1     2        
1     5
2     5
3     4

数据帧DF2是DF1中Id1列中的成对值集合,它们在DF1的Id2中共享一个公共值。

我的尝试:

temp <- do.call("cbind", split(DF1, rep(c(1,2), length.out = nrow(DF1))))
(DF2 <- temp %>% select("1.Id1", "2.Id2")) 

但这不会生成成对的数据帧:

Id1 Id2
1     2
3     4

4 个答案:

答案 0 :(得分:2)

您可以根据split中的值Id1 Id2并使用combn创建所有可能的组合并绑定结果。

do.call(rbind, lapply(split(df$Id1, df$Id2), function(x) t(combn(x, 2))))

#     [,1] [,2]
#[1,]    3    4
#[2,]    1    2
#[3,]    1    5
#[4,]    2    5

我们也可以使用较短的by

do.call(rbind, by(df$Id1, df$Id2, function(x) t(combn(x, 2))))

答案 1 :(得分:2)

我们可以使用tidyverse方法,将“ Id2”分组,获取“ {1”的combn,将其嵌套为宽格式并重命名列

library(dplyr)
library(tidyr)
library(stringr)
DF1 %>%
    # // group by Id2
    group_by(Id2) %>%
    # // get the combinations in summarise
    summarise(out = combn(Id1, 2, simplify = FALSE)) %>% 
    ungroup %>%
    # // unnest to wide format
    unnest_wider(c(out)) %>% 
    select(-Id2) %>%
    rename_all(~ str_c("V", seq_along(.)))
# A tibble: 4 x 2
#     V1    V2
#  <int> <int>
#1     3     4
#2     1     2
#3     1     5
#4     2     5

数据

DF1 <- structure(list(Id1 = 1:5, Id2 = c(10L, 10L, 7L, 7L, 10L)),
class = "data.frame", row.names = c(NA, 
-5L))

答案 2 :(得分:2)

这是使用tidyverse的另一种full_join方法。

library(dplyr)
library(purrr)

dat2 <- dat %>%
  full_join(dat, by = "Id2") %>%
  filter(Id1.x != Id1.y) %>%
  mutate(Id_sort = map2_chr(Id1.x, Id1.y, ~paste(sort(c(.x, .y)), collapse = ", "))) %>%
  distinct(Id_sort, .keep_all = TRUE) %>%
  select(Id1 = Id1.x, Id2 = Id1.y)
dat2
#   Id1 Id2
# 1   1   2
# 2   1   5
# 3   2   5
# 4   3   4

数据

dat <- read.table(text = "Id1 Id2 
1     10
2     10
3     7
4     7
5     10",
                  header = TRUE)

答案 3 :(得分:2)

也可以将其概念化为网络/图形问题:

df1 <- data.frame(Id1 = 1:5, Id2 = c(10L, 10L, 7L, 7L, 10L))

library(igraph)
g <- graph.data.frame(df1)
g <- connect(g, 2)
g <- induced_subgraph(g, V(g) %in% df1$Id1)
as_edgelist(g)
#     [,1] [,2]
#[1,] "1"  "2" 
#[2,] "1"  "5" 
#[3,] "2"  "5" 
#[4,] "3"  "4"