# How to read data from external files into R and save them as a time series (ts) object? # Simple but tedious: typing data as a vector (only useful for very short series): my.data = c(12,31,22,24,30) # Converting it to a 'ts' object (Suppose these are QUARTERLY data beginning at the second quarter of 2006): dat2 = ts(my.data, start=c(2006,2), frequency=4) # Check the created object: print(dat2) # print the observed data values time(dat2) # print the times at which the measurements were taken ######################################################## # What if the data are in an external data file, with the data values separated by spaces, tabs, or line breaks? # Suppose the file were called 'file1.txt': # Note: before running this code, go to # File -> Change dir # in R, and navigate to the directory on your computer in which 'file1.txt' is stored. # On a Mac, the correct menus to go to in order to change directory are: # Misc --> Change Working Directory # or in RStudio on a Mac: # Session --> Set Working Directory --> Choose Directory dat2 = ts(scan('file1.txt'), start=c(2006,2), frequency=4) # What if there were several (say, 3) lines at the top of the data file that were just # descriptions of the data, not real data values, which we want to skip over? # Use the 'skip' argument: dat2 = ts(scan('file1.txt', skip=3), start=c(2006,2), frequency=4) # What if the data are in a multicolumn table, with one column containing the time values # and the other column containing the data values, like this: Time Response 2006.Qtr2 12 2006.Qtr3 31 2006.Qtr4 22 2007.Qtr1 24 2007.Qtr2 30 # Suppose the file were called 'file2.txt': # Note: On WINDOWS, before running the following code, go to # File -> Change dir # in R, and navigate to the directory on your computer in which 'file2.txt' is stored. # On a Mac, see above for the instructions for changing directory. dat3 = read.table('file2.txt', header=T) # this is if the first line of the data file is a column with the variable names dat3 = read.table('file2.txt', header=F) # this is if the data start on the first line, with no header # Then converting it to a 'ts' object: Yvec = dat3[,2] # picks out 2nd column of dat3 dat3.ts = ts(Yvec, start=c(2006,2), frequency=4) # What if the data are in an Excel file? # First save the Excel file as a .csv file. # Note: before running this code, go to # File -> Change dir # in R, and navigate to the directory on your computer in which 'file3.csv' is stored. dat4 = read.csv('file3.csv', header=T) # Then convert to data vector to a 'ts' object as shown above. # Please read the section labeled "Reading time series data" on the web page that I link to # on the link labeled "Examples for reading in Time Series and creating 'ts' objects in R" # on our course web page!!