【问题标题】:How to turn monadic into dyadic data in R?如何在R中将一元数据转换为二元数据?
【发布时间】:2015-11-02 17:30:59
【问题描述】:

注意:这是How do I turn monadic data into dyadic data in R (country-year into pair-year)?的修改版本

我有按国家/地区组织的数据,并带有一个二元关系的 ID。我想按 dyad-year 组织这个。

这是我的数据的组织方式:

   dyadic_id country_codes year
1          1           200 1990
2          1            20 1990
3          1           200 1991
4          1            20 1991
5          1           200 1991
6          1           300 1991
7          1           300 1991
8          1            20 1991
9          2           300 1990
10         2            10 1990
11         3           100 1990
12         3            10 1990
13         4           500 1991
14         4           200 1991

这是我想要的数据:

  dyadic_id_want country_codes_1 country_codes_2 year_want
1              1             200              20      1990
2              1             200              20      1991
3              1             200             300      1991
4              1             300              20      1991
5              2             300              10      1990
6              3             100              10      1990
7              4             500             200      1991

这是可重现的代码:

dyadic_id<-c(1,1,1,1,1,1,1,1,2,2,3,3,4,4)
country_codes<-c(200,20,200,20,200,300,300,20,300,10,100,10,500,200)
year<-c(1990,1990,1991,1991,1991,1991,1991,1991,1990,1990,1990,1990,1991,1991)
mydf<-as.data.frame(cbind(dyadic_id,country_codes,year))


dyadic_id_want<-c(1,1,1,1,2,3,4)
country_codes_1<-c(200,200,200,300,300,100,500)
country_codes_2<-c(20,20,300,20,10,10,200)
year_want<-c(1990,1991,1991,1991,1990,1990,1991)
my_df_i_want<-as.data.frame(cbind(dyadic_id_want,country_codes_1,country_codes_2,year_want))

这是一个独特的问题,因为有多个国家/地区参加每项活动(以 dyadic_id 表示)。

【问题讨论】:

标签: r


【解决方案1】:

实际上,您可以非常类似于 akrun's solutiondplyr 执行此操作。不幸的是,我对data.table 不够精通,无法为您提供帮助,我相信其他人可能对此有更好的解决方案。

基本上,对于mutate(ind=...) 部分,您需要更加聪明地了解如何构建此指标,以便它是独一无二的,并会导致您正在寻找的相同结果。对于我的解决方案,我注意到由于您有两个一组,那么您的指标应该只附加modulus 运算符。

ind=paste0('country_codes', ((row_number()+1) %% 2+1))

然后,您需要为每组两个标识符创建一个标识符,该标识符可以再次使用类似的想法构建。

ind_row = ceiling(row_number()/2)

然后您可以在代码中正常进行。

完整代码如下:

mydf %>% 
  group_by(dyadic_id, year) %>%
  mutate(ind=paste0('country_codes', ((row_number()+1) %% 2+1)), 
         ind_row = ceiling(row_number()/2)) %>%
  spread(ind, country_codes) %>% 
  select(-ind_row)
#  dyadic_id year country_codes1 country_codes2
#1         1 1990            200             20
#2         1 1991            200             20
#3         1 1991            200            300
#4         1 1991            300             20
#5         2 1990            300             10
#6         3 1990            100             10
#7         4 1991            500            200

所有功劳都归功于 akrun 的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2022-01-23
    • 2023-03-08
    • 2012-06-18
    • 2013-06-04
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多