【问题标题】:Create dyadic (relational) data from monadic data从一元数据创建二元(关系)数据
【发布时间】:2022-10-17 20:51:00
【问题描述】:

我有看起来像这样的冲突数据

conflict_ID country_code   SideA
1              1             1          
1              2             1 
1              3             0
2              4             1
2              5             0 

现在我想把它变成这样的二元冲突数据(SideA=1 应该是country_code_1):

conflict_ID country_code_1 country_code_2 
1              1             3          
1              2             3 
2              4             5

谁能指出我正确的方向?

【问题讨论】:

  • 我的回答对你有用吗?

标签: r dataframe combinations


【解决方案1】:

这扩展了您发布的previous issue。您可以为每个conflict_ID 生成所有组合,并过滤掉country_code_2 匹配country_codeSideA == 1 的那些组合。

library(dplyr)
library(tidyr)

mydf %>%
  group_by(conflict_ID) %>%
  summarise(country_code = combn(country_code, 2, sort, simplify = FALSE),
            .groups = 'drop') %>%
  unnest_wider(country_code, names_sep = '_') %>%
  anti_join(filter(mydf, SideA == 1),
            by = c("conflict_ID", "country_code_2" = "country_code"))

# # A tibble: 3 × 3
#   conflict_ID country_code_1 country_code_2
#         <int>          <int>          <int>
# 1           1              1              3
# 2           1              2              3
# 3           2              4              5

【讨论】:

  • error: Join columns must be present in data. x Problem with `country_code_2`. Run `rlang::last_error()` to see where the error occurred. &gt; rlang::last_error() &lt;error/rlang_error&gt; Join columns must be present in data. x Problem with `country_code_2`. Backtrace: 1. `%&gt;%`(...) 3. dplyr:::anti_join.data.frame(...) 4. dplyr:::join_filter(x, y, by = by, type = "anti", na_matches = na_matches) 5. dplyr:::join_cols(tbl_vars(x), tbl_vars(y), by = by) 6. dplyr:::standardise_join_by(by, x_names = x_names, y_names = y_names) 7. dplyr:::check_join_vars(by$x, x_names)
  • 嘿,谢谢你的帮助。不幸的是,我收到上面发布的错误。有任何想法吗?
  • @craszer,您弄乱了列名。你的代码是什么?
  • 我的代码是:``` MIDdyadic <- MID2014 %>% group_by(dispnum) %>% summarise(iso3 = combn(iso3, 2, sort, simple = FALSE), .groups = 'drop') %>% unnest_wider( iso3, names_sep = '_') %>% anti_join(filter(MID2014, sidea == 1), by = c("dispnum", "iso3nr2" = "iso3")) ``` 所有列名都是实际列名从数据中,除了不是实际列的 vor "iso3nr2" (对应于您的代码,对吗?)
  • @craszer anti_join(filter(MID2014, sidea == 1), by = c("dispnum", "iso3_2" = "iso3"))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多