如何计算R中的分数/指标?

时间:2015-11-04 05:13:47

标签: r

我想尝试计算得分或创建一个指数,该指数给出了世界经济中国家“边缘化”的程度。换句话说,一个指数表明国家在世界经济中的地位。

基本上,我试图复制别人的指标。他将世界经济中的“边缘化”定义为该国占世界贸易百分比的函数。

通过计算得出:进口总额+某一国家的总出口额除以世界经济的总进口额+出口额。它的倒数除以100.

我试图弄清楚如何使用我的数据在R中计算它。下面我给出一个(真实的)例子。

Country  Year     EXPORT(current$)  IMPORT(c$)          GDP(c$) 
    A        2001        8,38177(..)   8,31506           3,78(+11)                    
    B        2001        1,90875(..)   1,71328           5,387293(..)
    C        2001        5,1872(..)    5,87710           1,90
    WORLD    2001        7,6811(..)    7,7101            3,30(+13)

很明显,我想在我的数据中计算每个国家和地区的分数(约150个国家,从1990年到2014年)。等式(再次清楚):进口+出口(对于数据集中的给定国家)/进口+出口(世界经济,请参见示例中的变量“WORLD”。

编辑:当前$的另一个例子(如果这有任何帮助)

{{1}}

2 个答案:

答案 0 :(得分:2)

使用好旧的data.table:

library( data.table)

# Thanks "TheKevinNeville" for the sample data!
country <- c("A", "B", "C", "World")
year <- c(rep(2001, 4), rep(2002, 4))
export <- abs(rnorm(8) * 5)
import <- abs(rnorm(8) * 5)
dt <- data.table( country,year,export,import)

# Here you calculate the index (rank) per group
dt[,index := (import + export) / .SD[country=="World", import + export],by=.(year)]

结果如下:

   country year   export    import    index
1:       A 2001 4.641794 7.3788739 6.222089
2:       B 2001 4.286842 1.3656420 2.925816
3:       C 2001 1.919439 1.1210429 1.573802
4:   World 2001 1.164199 0.7677355 1.000000
5:       A 2002 1.303430 3.5848178 1.478056
6:       B 2002 4.231528 2.6427575 2.078573
7:       C 2002 8.655763 7.1272979 4.772314
8:   World 2002 2.134707 1.1725057 1.000000

如果您想订购每年的结果和索引(降序),您可以添加以下代码:

# setorder reorders the rows of a data.table by reference,
# based on the columns provided. 
setorder(dt, year, -index)

答案 1 :(得分:-1)

创建数据。

country <- c("A", "B", "C", "World")
year <- c(rep(2001, 4), rep(2002, 4))
export <- abs(rnorm(8) * 5)
import <- abs(rnorm(8) * 5)

mydf <- data.frame(country=country,Year=year,EXPORT=export, IMPORT=import)

For loop。

mydf$Score <- NA
for(i in 2001:2002){
index <- mydf[,"Year"] == i
current_world <- mydf$country[index] == "World"
mydf$Score[index] <- (mydf$EXPORT[index] + mydf$IMPORT[index]) / (mydf$EXPORT[index][current_world] + mydf$IMPORT[index][current_world])
}
相关问题