How to select row which have sub rows?

Viewed 129

These days I am working with R and I use to use h02 data-set. This data-set can be import by

library(fpp)
data <- h02
data

When I ran above the code I got this output.

           Jan       Feb       Mar       Apr       May       Jun       Jul       Aug       Sep       Oct       Nov       Dec
1991                                                             0.4297950 0.4009060 0.4321590 0.4925430 0.5023690 0.6026520
1992 0.6601190 0.3362200 0.3513480 0.3798080 0.3618010 0.4105340 0.4833887 0.4754634 0.5347610 0.5686061 0.5952233 0.7712578
1993 0.7515028 0.3875543 0.4272832 0.4138902 0.4288588 0.4701264 0.5092097 0.5584430 0.6015141 0.6329471 0.6996054 0.9630805
1994 0.8193253 0.4376698 0.5061213 0.4704912 0.5106963 0.5405138 0.5581189 0.6728521 0.6858974 0.6896920 0.7413036 0.8133076
1995 0.8031126 0.4752582 0.5525723 0.5271078 0.5612498 0.5889776 0.6231336 0.7408372 0.7253718 0.8158030 0.8140095 0.9266531
1996 0.9372759 0.5287616 0.5593399 0.5778717 0.6149274 0.5941888 0.7077584 0.7195020 0.7443237 0.8048551 0.7885423 0.9710894

That was the sample of full data-set. My problem is when I tried to view first row of the data-set I used this command

head(data, 1)

That should be output first row of the data-set but I have got this output

          Jul
1991 0.429795

But my expected output is

           Jan       Feb       Mar       Apr       May       Jun       Jul       Aug       Sep       Oct       Nov       Dec
1991                                                             0.4297950 0.4009060 0.4321590 0.4925430 0.5023690 0.6026520

When I check columns, This data-set have no columns and have only rows. each year row has sub month rows. How can I select year row with all month rows?

2 Answers

This is because data isn't a datafame, it's a time-series object. You can check this

str(data)
Time-Series [1:204] from 1992 to 2008: 0.43 0.401 0.432 0.493 0.502 ...

First convert data to a dataframe, then your head command will work as you expect.

Month <-  factor(cycle(data), levels = 1:12, labels = month.abb)
df <- tapply(data, list(year = floor(time(data)), month = Month), c)
head(df, 1)

      month
year   Jan Feb Mar Apr May Jun      Jul      Aug      Sep      Oct      Nov      Dec
  1991  NA  NA  NA  NA  NA  NA 0.429795 0.400906 0.432159 0.492543 0.502369 0.602652

I have found the another solution for this. It is window() keyword and you have to give the start year, month and end year, month to get specific row.

window(data, start=c(1991,1), end=c(1991,12))

Output -:

          Jul      Aug      Sep      Oct      Nov      Dec
1991 0.429795 0.400906 0.432159 0.492543 0.502369 0.602652

From Jan to Jun time series have 0 values there for those months not counted.

Related