【问题标题】:Calculate percent changes in "long" dataframe计算“长”数据框中的百分比变化
【发布时间】:2012-11-20 22:04:59
【问题描述】:

我有一个数据框,其中包含按国家/地区列出的 GDP 值以及随附的日期列。以下代码重现了两个国家(法国和德国)和六年(2005-2010)的示例数据集:

df <- structure(list(geo = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 
                2L, 2L, 2L, 2L, 2L), .Label = c("DE", "FR"), class = "factor"), 
                 date = structure(c(12784, 13149, 13514, 13879, 14245, 14610, 
                 12784, 13149, 13514, 13879, 14245, 14610), class = "Date"), 
                 GDP = c(2147975, 2249584.4, 2373993.1, 2382892.6, 2224501.8, 
                2371033.2, 1557584.8, 1621633.2, 1715655.4, 1713157.1, 1636336.3, 
               1707966.5)), .Names = c("geo", "date", "GDP"), row.names = c(NA, 
              -12L), class = "data.frame")

现在我想计算一个额外的列,显示每年的百分比差异。我尝试以下方法:

library(quantmod) 
# provides the Delt() function to calculate percent differences

df$dtGDP <- as.numeric(Delt(df$GDP))

这是错误的,因为它使用 2010 年的 DE 值计算 2005 年的 FR 值。有没有办法应用“按因子水平”函数?

【问题讨论】:

  • 这是一个非常典型的“split-apply-combine”问题,您可能会在 SO 上找到大量答案。
  • @BenBarnes 我仍然喜欢下面的 DWin 答案!
  • 实际上@BenBarnes 可能是正确的。如果您搜索tapply 和“ave”,您可能会发现很多与我的非常相似的示例。 (另一方面,你会发现很多 plyr-package 函数的工作示例,它们本质上是彼此同构的。)

标签: r


【解决方案1】:
> df$dtGDP <-with(df, ave(GDP, geo, FUN=Delt))
> df
   geo       date     GDP        dtGDP
1   DE 2005-01-01 2147975           NA
2   DE 2006-01-01 2249584  0.047304741
3   DE 2007-01-01 2373993  0.055302971
4   DE 2008-01-01 2382893  0.003748747
5   DE 2009-01-01 2224502 -0.066469970
6   DE 2010-01-01 2371033  0.065871558
7   FR 2005-01-01 1557585           NA
8   FR 2006-01-01 1621633  0.041120329
9   FR 2007-01-01 1715655  0.057979943
10  FR 2008-01-01 1713157 -0.001456178
11  FR 2009-01-01 1636336 -0.044841655
12  FR 2010-01-01 1707966  0.043774742

【讨论】:

  • 太棒了!我在两行中执行,而您在单个命令中执行
【解决方案2】:

试试这个:

foo <- aggregate(GDP~geo, df, function(x) list(Delt(x)))
df <- cbind(df, dtGDP = as.numeric(unlist(foo[,-1])))
df

假设你已经运行了这个:

library(quantmod) 
df <- structure(list(geo = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 
                2L, 2L, 2L, 2L, 2L), .Label = c("DE", "FR"), class = "factor"), 
                date = structure(c(12784, 13149, 13514, 13879, 14245, 14610, 
                12784, 13149, 13514, 13879, 14245, 14610), class = "Date"), 
                GDP = c(2147975, 2249584.4, 2373993.1, 2382892.6, 2224501.8, 
                2371033.2, 1557584.8, 1621633.2, 1715655.4, 1713157.1, 1636336.3, 
                1707966.5)), .Names = c("geo", "date", "GDP"), row.names = c(NA, 
                -12L), class = "data.frame")

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    相关资源
    最近更新 更多