【问题标题】:reshape function gives "subscript out of bounds" errorreshape 函数给出“下标越界”错误
【发布时间】:2012-10-21 14:41:58
【问题描述】:

我有一个如下所示的 ROC.Value 数据框:

Years   1           2   3       4   5
2002    3.000000    NA  0.22    NA      0
2003    2.988000    NA  0.22    NA      0
2004    2.993976    NA  0.22    NA      0
2005    3.071819    NA  0.22    NA      NA
2006    3.314493    NA  0.22    NA      NA
2007    3.526621    NA  0.22    NA      NA
2008    3.583047    NA  0.22    NA      NA
2009    4.109754    NA  0.22    NA      NA
2010    4.085096    NA  0.22    3.00    NA
2011    3.885096    NA  0.22    2.85    NA
2012    3.685096    NA  0.22    2.70    NA
2013    3.485096    NA  0.22    2.55    NA
2014    3.285096    NA  0.22    2.40    NA
2015    3.085096    NA  0.22    2.25    NA
2016    2.885096    NA  0.22    2.10    NA
2017    2.685096    NA  0.22    1.95    NA
2018    2.485096    NA  0.22    1.80    NA
2019    2.285096    NA  0.22    1.65    NA
2020    2.085096    NA  0.22    1.50    NA
2021    1.885096    NA  0.22    1.50    NA

当我得到正确的数据时,NA 值将被替换。

当我使用以下代码尝试将其转换为长格式时(这样我就可以制作堆叠箱线图):

m.ROC.Value = reshape(ROC.Value, 
                  idvar="Years", 
                  direction="long", 
                  varying=list(colnames(ROC.Value[2:6])),
                  timevar="Characteristic"
                  )

我收到此错误Error in reshapeLong(data, idvar = idvar, timevar = timevar, varying = varying, : subscript out of bounds

有什么建议吗?我尝试的一切都没有成功(出现新错误)。

【问题讨论】:

  • 您的代码在我的系统上运行没有任何问题。
  • 嗯。我正在运行 R 版本 2.15.1 和 reshape2 包。和你一样吗?
  • 我正在运行相同版本的 R。如果您将第 2 列重命名为第 6 列,它可能会起作用。它们以(是)数字开头可能是个问题。
  • 我也试过这个(从非数字名称开始,然后改变它,但它没有解决问题)。我只是给了我subscript out of bounds 错误。

标签: r reshape reshape2


【解决方案1】:

函数reshape 是R 的基函数,而不是reshape2。如果你想使用reshape2,使用这个命令:

melt(as.data.frame(ROC.Value), measure.vars = 2:6)

【讨论】:

  • 我也试过这个功能。但是它将所有列都变成了测量变量——即使我指定它应该只是 2:6 列。它看起来像这样:pastebin.com/pcnv38Gm
  • @bonna str(ROC.Value) 的结果是什么。
  • num [1:20, 1:6] 2002 2003 2004 2005 2006 ... - attr(*, "dimnames")=List of 2 ..$ : NULL ..$ : chr [ 1:6] “年” “1” “2” “3” ...
  • @bonna 我想如果您在使用melt 之前将ROC.Value 转换为数据框,您的问题就可以解决。请参阅我的答案的更新。如果我使用 ROC.Value 作为矩阵,我可以重现您的错误消息。
【解决方案2】:

这是一个愚蠢的解决方法 - 但它有效。 我没有立即添加年份列,而是在使用 melt() 函数后添加了它。

#Don't add years here
#ROC.Value = cbind(years, Buy.Out.Value, Recycled.Green.Premium, Levy.Exemption.Certificate, Energy.Value, CO2.Price, deparse.level = 1)
ROC.Value = cbind(Buy.Out.Value, Recycled.Green.Premium, Levy.Exemption.Certificate, Energy.Value, CO2.Price, deparse.level = 1)
m.ROC.Value = melt(ROC.Value)
#Add years here (runs from 2002, so using id+2001)
m.ROC.Value = cbind(m.ROC.Value, m.ROC.Value$Var1 + rep(2001, 100))
colnames(m.ROC.Value) = c("id", "measure", "value", "years")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2019-08-26
    • 2015-04-03
    相关资源
    最近更新 更多