2013-08-01 56 views
0

我有意大利,西班牙,美國等幾個國家和幾年的時間序列數據。我想將一些國家的數據相對於繪製到另一個國家:比如說將意大利和西班牙的實際人均國內生產總值與美國的百分比進行比較。一個國家相對於另一個國家的情節變量

這就是數據的模樣:

head(pwt) 
     country isocode  year  rgdpo  pop 
ESP-1950 Spain  ESP 1950-01-01 85002.27 27.99278 
ESP-1951 Spain  ESP 1951-01-01 100241.94 28.22724 
ESP-1952 Spain  ESP 1952-01-01 105170.11 28.47847 
ESP-1953 Spain  ESP 1953-01-01 101322.59 28.73209 
ESP-1954 Spain  ESP 1954-01-01 114573.78 28.98774 
ESP-1955 Spain  ESP 1955-01-01 120839.95 29.24542 

感興趣的變量在這裏,「真正的人均GDP」,獲得了rgdpo/pop

可悲的是,我沒有得到很遠。我知道如何選擇一個整列,例如pwt['rgdpo']pwt$rgdpo,但後來不確定如何將這個限制在特定的國家而沒有完全拆除數據框。 (我會知道如何通過使用子集函數爲每個國家創建變量,然後通過劃分然後重新創建一個數據框然後創建相關變量,然後繪圖,但我想要在這裏學習聰明的方法)。

我想該解決方案是穩健的NAS或丟失日期存在(缺少的日期可能將由NAS代替)

我在我的例子中使用GGPLOT2,但我很開放的態度到一個base-R解決方案也是如此(作者:Hadley Wickham,Winston Chang,http://cran.r-project.org/web/packages/ggplot2/)。

爲了獲得一個可重複的例子,我從pwt8包中獲取數據(作者:Achim Zeileis,http://cran.r-project.org/web/packages/pwt8/)。

# Get data 
# install.packages("pwt8") 
library("pwt8") 
data("pwt8.0") 
# names(pwt8.0) 

# use -subset- to get specifc countries and variables. 
countries <- c("USA", "ESP", "ITA") 
variables <- c("country", "isocode", "year", "rgdpo", "pop") 
pwt <- subset(pwt8.0, isocode %in% countries, select = variables) 

# Plot GDP PER CAPITA with ggplot 
library("ggplot2") 
pwt$year<-as.Date(paste0(pwt$year,"-01-01"),format="%Y-%m-%d") # year as Date 
ggp <- ggplot(pwt,aes(x=year,y=rgdpo/pop,color=as.factor(isocode),group=isocode)) + 
geom_line() 
ggp <- ggp + 
xlab("") + 
ylab("") + 
ggtitle("Real GDP Per Capita (international $, 2005 prices, chain)") + 
theme(legend.title = element_blank()) + 
coord_trans(y = "log10") 
ggp <- ggp + coord_cartesian(xlim=as.Date(c("2000-01-01","2012-01-01")),ylim=c(22000,45000)) 
ggp 

enter image description here

解決方案:感謝香港大井!

require("plyr") 
pwt <- ddply(pwt, .(country), transform, gdppc.usa=(rgdpo/pop)/within(subset(pwt, isocode=="USA"),gdppc<-rgdpo/pop)$gdppc) 
library("ggplot2") 
ggp <- ggplot(subset(pwt,isocode==c("ESP","ITA")),aes(x=year,y=gdppc.usa,color=as.factor(isocode),group=isocode)) + 
geom_line() 
ggp <- ggp + 
    xlab("") + 
    ylab("") + 
    ggtitle("Real GDP Per Capita Relative to USA (international $, 2005 prices, chain)") + 
    theme(legend.title = element_blank()) 
ggp 

enter image description here

回答

3

繪製之前將您的數據:

require(plyr) 
usa <- within(subset(pwt8.0, isocode=="USA"), gdppop <- rgdpo/pop) 

# send this to ggplot2 
dat <- ddply(pwt8.0, .(country), transform, gdppop_usa=(rgdpo/pop)/usa$gdppop) 
+0

感謝香港大井。不幸的是,這是行不通的。我認爲這兩條線都不會做它打算做的事情。第一行爲人均GDP創造了一個變量。內部使用子集似乎沒有效果。第一行給出了與_pwt < - 內(pwt,gdppc < - rgdpo/pop)相同的結果_任何想到這是爲什麼?第二行將西班牙人均國內生產總值除以西班牙人均國內生產總值等,這樣dat中的變量gdppop_usa等於1 ... – PatrickT

+0

Gah,typo。 'country =「USA」'應該是'country ==「USA」'。 –

+0

我明白了!非常感謝。實際上,而不是「國家」,它應該是「isocode」,「美國」< - 子集(pwt,isocode ==「USA」),gdppop < - rgdpo/pop)' – PatrickT

相關問題