2013-05-18 49 views
3

嗨,我是R新手,有一個問題。我有一個data.frame(df),其中包含大約來自100多個不同國家的1960 - 2012年的約30種不同類型的統計數據。這裏是什麼樣子的例子:R - 創建包含來自另一個data.frame操縱數據data.frame的函數

 Country  Statistic.Type  1960  1961  1962  1963 ... 2012 
__________________________________________________________________________________ 
1 Albania  Death Rate   10  21  13  24  25 
2 Albania  Birth Rate   7   15  6   10  9 
3 Albania  Life Expectancy  8   12  10  7   20 
4 Albania  Population   10  30  27  18  13 
5 Brazil  Death Rate   14  20  22  13  18 
6 Brazil  Birth Rate   ... 
7 Brazil  Life Expectancy  ... 
8 Brazil  Population   ... 
9 Cambodia  Death Rate   ... 
10 Cambodia  Birth Rate   ...     etc... 

注意,有55列共和值在每53個YEAR列的是彌補了這個問題的目的。

我需要幫助編寫一個函數,它將輸入的國家和統計類型作爲輸入,並返回一個新的data.frame,其中包含2列,顯示給定國家和統計類型每年的年份和值。例如,如果我輸入國=巴西和statistic.type =死亡率進入功能,新data.frame應該是這樣的:

 Year Value 
_____________________ 
1 1960  14 
2 1961  20 
3 1962  22 
... 
51 2012  18 

我對如何做到這一點不知道,如果任何人都可以給我安裝任何想法/代碼/軟件包,那將是非常有幫助的。

太謝謝你了!

+0

請仔細閱讀本並提供對數據的最小可重複比如http:/ /stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Dason

+0

嗨@ user2397274,如果您認爲您的問題已得到滿意的回答,您是否可以考慮接受下面的答案之一? :-) –

回答

1

如果df是你data.frame,所有你需要的是這樣的:

f <- function(country, statistic.type, data=df) 
{ 
values <- data[data$Country==country & data$Statistic.Type==statistic.type,-(1:2)] 

cbind(Year=names(df)[-(1:2)], Value=values) 
} 

使用它作爲

f(country="Brazil", statistic.type="Death Rate") 
0

你可以只結合subsetstack,在那裏也許gsub在你的年柱只留下數字:

df <- expand.grid(
    "country" = c("A", "B"), 
    "statistic" = c("c", "d", "e", "f"), 
    stringsAsFactors = FALSE) 

df$year1980 <- rnorm(8) 
df$year1990 <- rnorm(8) 
df$year2000 <- rnorm(8) 


getYears <- function(input, cntry, stat) { 
    x <- subset(input, country == cntry & stat == statistic, 
    select = -c(country, statistic)) 
    x <- stack(x)[,c("ind", "values")] 
    x$ind <- gsub("\\D", "", x$ind) 
    x 
} 


getYears(df, "A", "c") 

    ind  values 
1 1980 1.1421309 
2 1990 1.0777974 
3 2000 -0.2010913 
相關問題