ali ali - 3 months ago 14
R Question

Getting last 100 value of a ts object in R

I have a data as below.

cotton <- structure(list(V1 = c(52L, 49L, 49L, 44L, 47L, 52L, 45L, 51L,
54L, 57L, 67L, 71L, 66L, 65L, 75L, 66L, 70L, 70L, 69L, 71L, 70L,
72L, 73L, 73L, 75L, 69L, 77L, 75L, 71L, 74L, 69L, 71L, 70L, 78L,
74L, 72L, 74L, 72L, 73L, 73L, 72L, 70L, 73L, 71L, 76L, 79L, 68L,
79L, 76L, 78L, 78L, 78L, 75L, 75L, 73L, 78L, 78L, 78L, 81L, 80L,
79L, 84L, 82L, 81L, 80L, 83L, 77L, 81L, 82L, 83L, 82L, 86L, 78L,
82L, 81L, 79L, 79L, 80L, 75L, 78L, 78L, 77L, 80L, 80L, 80L, 82L,
81L, 84L, 83L, 82L, 84L, 81L, 80L, 83L, 87L, 81L, 84L, 84L, 82L,
84L, 83L, 84L, 82L, 80L, 78L, 84L, 84L, 84L, 82L, 84L, 79L, 82L,
79L, 79L, 72L, 73L, 78L, 82L, 83L, 81L, 77L, 75L, 70L, 71L, 66L,
59L, 57L, 62L, 60L, 58L, 59L, 56L, 53L, 55L, 56L, 57L, 62L, 58L,
56L, 60L, 63L, 66L, 71L, 74L, 70L, 74L, 75L, 74L, 77L, 79L, 76L,
77L, 79L, 80L, 81L, 78L, 77L, 78L, 77L, 75L, 71L, 66L, 63L, 57L,
55L, 55L, 55L, 54L, 57L, 57L, 53L, 54L, 60L, 63L, 65L, 64L, 68L,
74L, 73L, 74L, 75L, 73L, 77L, 75L, 76L, 68L, 73L, 49L, 69L, 80L,
82L, 78L, 71L, 70L, 73L, 71L, 68L, 72L, 70L, 43L, 72L, 81L, 81L,
80L, 73L, 73L, 72L, 68L, 71L, 73L, 67L, 43L, 68L, 69L, 77L, 78L
)), .Names = "V1", class = "data.frame", row.names = c(NA, -216L
))


I want to analyse last 100 values of this data frame. I use ts() function to convert it to a time series object with a known start and frequency. But when I take last 100 values as below,

cotton.ts <- ts(cotton, start = 2000, frequency = 12)
if(length(cotton.ts) > 100 ){
cotton.ts <- cotton.ts[(length(cotton.ts)-99):length(cotton.ts)]
}


cotton.ts becomes a vector. I need it to be a time series but frequency and start year is always changing. So I don't want to find new start year and month all the time to make it time series again. Is there a way to do this without loosing times?

Answer

I don't want to find new start year and month all the time to make it time series again. Is there a way to do this without loosing times?

I am afraid you have to do so. It is not difficult anyway. Below is an automatic way

u <- length(cotton.ts) - 99
ts(cotton.ts[u:length(cotton.ts)], start = c(2000 + floor(u / 12), u %% 12),
   frequency = 12)

#     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
#2009                                  78  82  83  81
#2010  77  75  70  71  66  59  57  62  60  58  59  56
#2011  53  55  56  57  62  58  56  60  63  66  71  74
#2012  70  74  75  74  77  79  76  77  79  80  81  78
#2013  77  78  77  75  71  66  63  57  55  55  55  54
#2014  57  57  53  54  60  63  65  64  68  74  73  74
#2015  75  73  77  75  76  68  73  49  69  80  82  78
#2016  71  70  73  71  68  72  70  43  72  81  81  80
#2017  73  73  72  68  71  73  67  43  68  69  77  78

Note the use of start = c(a, b) in ts().