The ts() function in R is returning the correct start and frequency but not end value which is 1 and not 179

54 views Asked by At

I need help converting a column of 179 observations from an excel file that holds 2 variables (days and values). After i try converting the dataframe with ts(as.vector(a1dataraw['x'], the vector returns with start=1 but also end=1 when it should be 179?

Can someone please identify where im going wrong?

library(TSA)

#Load data 
a1dataraw <- read.csv("assignment1data2024.csv", header=TRUE)
a1dataraw

#Convert to TS

a1data <- NA
a1data <- ts(as.vector(a1dataraw['x']), # Read correct column, which is 'x' here.
  start= 1)

a1data

Code input

Code output

The end value is 1 when it should be 179? The csv file has 2 columns with headers Trading days and x for the observations

data sample it goes up to 179 trading days: sample

2

There are 2 answers

3
GaëtanLF On

Using the parameter end and setting the length of your series should do the trick.

x <- c(1,2,3)
x_ts <- ts(x,start=1,end=length(x))
1
G. Grothendieck On

There are several problems:

  • the data in the question is an image so no one can reproduce it without tediously retyping it. Even then this does not guarantee that one would have exactly what you have. In the future please provide a minimal reproducible example in text form using dput. See the information at the top of the tag page for guidance on posting.
  • there is no point in assigning NA to a1data because it is just overwritten in the next line anyways as if it had never existed
  • as.vector(a1data['x']) is a one element list whose sole component contains the vector a1data$x. That is why it thinks you have one element.

Assuming that the time index is consecutive integers starting at 1 all we need is

ts(a1data$x)

For example, using the first 3 rows of the built-in data frame BOD which has 2 columns named Time and demand

BOD3 <- BOD[1:3, ]
BOD3
##   Time demand
## 1    1    8.3
## 2    2   10.3
## 3    3   19.0

ts(BOD3$demand)
## Time Series:
## Start = 1 
## End = 3 
## Frequency = 1 
## [1]  8.3 10.3 19.0