[R] Making part of a data frame into a time series

andrewH ahoerner at rprogress.org
Thu Nov 22 00:32:53 CET 2012


Dear folks –
I have a bunch of data frames where columns 1:(n-1) contain information
about a county, and columns n and higher contain a time series of monthly
observations on that county.  I wanted to get the data in columns n and
higher to be recognized as a bunch of time series. So I wrote a function
that was supposed to turn all the columns from a given column number on into
a time series:

# Convert the final cols of a data frame into a time series
MakeTS <- function(data.df, firstColNo, firstYear, firstSubNo = NULL, freq =
1){
  data.df[,firstColNo:ncol(data.df)] <-  ts(data =
data.df[,firstColNo:ncol(data.df)],
                                                                             
start = c(firstYear, firstSubNo), frequency = freq)
  data.df
 }

However it does not appear to work. The is.ts function will not let me test
a subset of the data frame:

> # Simplified example for check.
> AA <- data.frame(rbind(c("X", 1:12), c("Y", 1:12)))
> AA
  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13
1  X  1  2  3  4  5  6  7  8   9  10  11  12
2  Y  1  2  3  4  5  6  7  8   9  10  11  12

> BB <- MakeTS(AA, 2, 2010, 1, 12)
> is.ts(window(BB[,2], start = c(2010, 1), [1,2:13])
Error: unexpected '[' in "is.ts(window(BB[,2], start = c(2010, 1), ["

In addition, and to my great confusion, the values in columns 3 and higher
have all been replaced by ones:
> BB
  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13
1  X  1  1  1  1  1  1  1  1   1   1   1   1
2  Y  1  1  1  1  1  1  1  1   1   1   1   1

I am guessing that you are not allowed to define part of a data frame as a
time series, and that I will just have to give up on that idea. Is that
right?

And why is everything a one? Is ts using the default frequency instead of
the one I handed to it? And if so, why?

Offers of help or insight greatly appreciated.

Sincerely, andrewH




--
View this message in context: http://r.789695.n4.nabble.com/Making-part-of-a-data-frame-into-a-time-series-tp4650392.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list