在R中合并二元和一元数据集

在R中合并二元和一元数据集

本文介绍了在R中合并二元和一元数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R(使用Rstudio)中合并两个数据集。



第一个数据集是由两国之间的双边贸易流量(dyad)组成的战争数据集的相关性。第二个是来自Penn World Tables的每个国家的GDP统计数据。我想知道如何合并数据集,以便每个二进制对应的国家1的国内生产总值和国内生产总值的国家2。



两个数据集都按照3个字符代码。第一个二元数据集具有以下列:Country1,country2,flow1,flow2,distance



第二个单体数据集有国家和国内生产总值。



我想添加GDP数据,以便新数据集现在为:
Country1,country2,flow1,flow2,distance,gdp1,gdp2。



有谁知道如何在R中合并这些集合?



提前感谢=)

解决方案

如果您想要具体答案,您应该发布可复制的数据样本。这对于有向和无向的二元组都是有效的。假设你的国家代码为二进制df是 ccode1 ccode2 ,你的dfs命名为 dy分别为.df mon.df

  new.df<  -  merge(dy.df,mon.df,by = c('ccode1','year'),all.x = TRUE)
new.df< - merge .df,mon.df,by = c('ccode2','year'),all.x = TRUE)

然后你可以清除你的数据集。您还确定您有ISO代码?大多数COW的东西都使用COW代码,而不是ISO代码。我还建议您阅读 merge 命令中的文档。 help(merge)


I am currently attempting to merge two datasets in R (using Rstudio).

The first dataset is dyadic consisting of bilateral trade flows between countries (dyad) from the Correlates of War dataset. The second is monadic data of GDP for each country from the Penn World Tables. I would like to know how to go about merging the datasets so that each dyad has the GDP of country 1 and GDP of country 2.

Both data sets are coded according to the 3 character isocodes. The first dyadic dataset has the following coloumns: Country1, country2, flow1, flow2, distance

The second monadic dataset has the country, and GDP.

I would like to add the GDP data so that the new data set will now be:Country1, country2, flow1, flow2, distance, gdp1, gdp2.

Does anyone know how i can merge these sets in R?

Thanks in advance =)

解决方案

You should post a replicable sample of your data if you want a specific answer. This should work for both directed and undirected dyads. Assuming your country codes for the dyadic df are ccode1 and ccode2 and your dfs are named dy.df and mon.df respectively.

new.df <- merge(dy.df, mon.df, by = c('ccode1', 'year'), all.x = TRUE)
new.df <- merge(dy.df, mon.df, by = c('ccode2', 'year'), all.x = TRUE)

Then you can clean out your data set from there. Also are you sure you have ISO codes? Most of the COW stuff uses COW codes, not ISO codes. I'd also suggest your read the documentation on the merge command. help(merge).

这篇关于在R中合并二元和一元数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:23