[英]Create a correlation data.frame based on text.values from another data.frame in R?
[英]R - Function to create a data.frame containing manipulated data from another data.frame
嗨,我是R的新手並且有一個問題。 我有一個data.frame(df),包含了1960年至2012年約100個不同國家的約30種不同類型的統計數據。 以下是它的外觀示例:
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年列中每列的值都是出於此問題的目的。
我需要幫助編寫一個函數,該函數將國家和統計類型作為輸入,並返回一個新的data.frame,其中包含2列,顯示給定國家/地區和統計類型的每年的年份和值。 例如,如果我在函數中輸入country = Brazil和statistic.type = Death Rate,則新的data.frame應如下所示:
Year Value
_____________________
1 1960 14
2 1961 20
3 1962 22
...
51 2012 18
我不知道如何做到這一點,如果有人可以給我任何想法/代碼/包安裝,那將是非常有幫助的。
非常感謝!
如果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")
您可能必須對總數據集執行一些拆分操作才能擁有國家/地區的數據集。 https://stat.ethz.ch/pipermail/r-help/2008-February/155328.html
然后對每個數據子集使用融合函數。 在您的情況下,改編自http://www.statmethods.net/management/reshape.html ,其中mydata是已經拆分的數據:
% example of melt function
library(reshape)
mdata <- melt(mydata, id=c("Year"))
這就對了。
您可以將subset
與stack
組合在一起,可能還有一個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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.