R 基于条件创建二元成对数据集

R 基于条件创建二元成对数据集,r,data-manipulation,pairwise,R,Data Manipulation,Pairwise,我有一个一元数据集,看起来像这样: df<-structure(list(Number = c("375_1", "375_1", "375_1", "375_1", "375_1", "375_1", "375_1", "375_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1"), year = c(1973,

我有一个一元数据集,看起来像这样:

df<-structure(list(Number = c("375_1", "375_1", "375_1", "375_1", 
"375_1", "375_1", "375_1", "375_1", "647_1", "647_1", "647_1", 
"647_1", "647_1", "647_1", "647_1", "647_1", "647_1", "647_1", 
"647_1", "647_1"), year = c(1973, 1973, 1973, 1973, 1973, 1973, 
1973, 1973, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 1981, 
1981, 1981, 1981), Country = c("AUT", "PRT", "CHE", "NOR", "SWE", 
"ISL", "DNK", "GBR", "BRA", "CHL", "EGY", "IND", "ISR", "MEX", 
"PER", "KOR", "PAK", "PHL", "TUN", "TUR")), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))
final <- data.frame(Number = c("375_1", "375_1", "375_1", "375_1", "375_1", "375_1", "375_1","375_1", "375_1", "375_1", "375_1","375_1"), 
                    year = c(1973, 1973, 1973, 1973, 1973, 1973, 1973, 1973,1973, 1973, 1973, 1973), 
                    Country1 = c("AUT", "AUT", "AUT", "AUT", "AUT", "AUT", "AUT","PRT","PRT","PRT","PRT","PRT"), 
                    Country2 = c("PRT", "CHE", "NOR", "SWE", "ISL", "DNK", "GBR","CHE","NOR","SWE", "ISL","DNK"),
                    stringsAsFactors = FALSE)     
在集团内的每一个国家继续这样做。 我想找到一种简洁明了的方法来做到这一点


非常感谢您的帮助

以供将来参考,我认为解决方案如下

final <- df %>% group_by(Number, year)%>%  expand(Country1 = Country, Country2= Country) %>% filter(Country1!=Country2)
final%groupby(Number,year)%%>%expand(Country1=Country,Country2=Country)%%>%filter(Country1!=Country2)

使用
tidyverse

library(tidyverse)

df %>%
  full_join(df, by=c("Number", "year")) %>%
  filter(Country.x != Country.y)

final
数据帧提供了最终输出的大致外观。因为我必须手工写,写所有的东西都要花很长时间。我想可以考虑<代码>最终< /COD>数据帧作为输出的<代码>头()>代码>。这意味着在实际输出中,我希望变量的每个值都有
Number
所有可能的二元组合。处理这个问题有什么想法吗?