bonna
bonna

Reputation: 1615

reshape function gives "subscript out of bounds" error

I have a ROC.Value data frame that looks like this:

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

The NA values will be replaced, when i get the correct data.

When i with the following code try and converting it into long format (so i can make a stacked boxplot):

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

I get this error Error in reshapeLong(data, idvar = idvar, timevar = timevar, varying = varying, : subscript out of bounds.

Any suggesting? Everything I tried didn't work out (gave a new error).

Upvotes: 2

Views: 3479

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

The function reshape is a base function of R, not of reshape2. If you want to use reshape2, use this command:

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

Upvotes: 2

bonna
bonna

Reputation: 1615

This is a stupid work around - but it works. Instead of adding the years column straight away, I added it after i have used the melt() function.

#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")

Upvotes: 0

Related Questions