subsetting list in R

2019-02-18 21:56发布

问题:

I'm using Mcomp package in R which contains dataset for forecasting.

The data is organized as yearly, quarterly and monthly frequencies. I can easily subset this into a list but cannot further subset using additional condition.

##Subset monthly data
library("Mcomp")
mon <- subset(M3,"monthly")

Each element in the mon list has following structure, as an example mon$N1500 has the following struture

$ N1500:List of 9
  ..$ st         : chr "M99"
  ..$ type       : chr "MICRO"
  ..$ period     : chr "MONTHLY"
  ..$ description: chr "SHIPMENTS (Code TD-30USA)"
  ..$ sn         : chr "N1500"
  ..$ x          : Time-Series [1:51] from 1990 to 1994: 3700 2460 3320 2480 3200 2980 3880 3320 3420 3780 ...
  ..$ xx         : Time-Series [1:18] from 1994 to 1996: 2400 2720 2840 2220 2320 2860 2980 2840 3000 3520 ...
  ..$ h          : num 18
  ..$ n          : int 51

My questions is how would I subset the mon to just get the $x for all the elements ans store it in a list with the same listname

for example see below for one element, I want to save this for all the elements in the mon list ?

> mon$N1500$x
      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
1990 3700 2460 3320 2480 3200 2980 3880 3320 3420 3780 4080 3160
1991 3440 3760 3020 2740 3800 3340 3920 2700 2460 2880 3120 3980
1992 3300 2740 3200 2540 3200 2780 2600 3020 2280 2720 2680 3060
1993 3040 2440 3380 2500 2540 3060 2560 2860 3320 2920 2560 3560
1994 3760 3140 2700 

Many Thanks

回答1:

You mean something like this?

x <- lapply(mon, `[[`, 'x')
str(x)
# List of 1428
#  $ N1402: Time-Series [1:50] from 1990 to 1994: 2640 2640 2160 4200 3360 2400 3600 1920 4200 4560 ...
#  $ N1403: Time-Series [1:50] from 1990 to 1994: 1680 1920 120 1080 840 1440 480 720 4080 1560 ...
#  $ N1404: Time-Series [1:50] from 1990 to 1994: 1140 720 4860 1200 3150 2130 1800 2010 2880 1650 ...
#  $ N1405: Time-Series [1:50] from 1990 to 1994: 180 940 2040 800 1000 520 500 400 1760 1520 ...
#  $ N1406: Time-Series [1:50] from 1990 to 1994: 2000 1550 4450 3050 3050 2250 2200 2450 4900 5300 ...
# ...