1
votes

I downloaded the unemployment data from 1980-2017 from the Bureau of Labor Statistics. I uploaded the file to R and tried to convert it to time series with as.ts(unemployment) but I'm not getting an appropriate graph. I have 13 columns, with the 1st column representing the Years with values from 1980-2017, and the other 12 columns representing the months and the values of unemployment. Ex:

as.ts(unemployment)

Time Series:

Start = 1

End = 38

Frequency = 1

Years Jan Feb Mar Apr May Jun Jul Aug Sep Oct

1 1980 6.3 6.3 6.3 6.9 7.5 7.6 7.8 7.7 7.5 7.5

2 1981 7.5 7.4 7.4 7.2 7.5 7.5 7.2 7.4 7.6 7.9

3 1982 8.6 8.9 9.0 9.3 9.4 9.6 9.8 9.8 10.1 10.4

November and december were suppressed because of space

2
Please consider some code example and output of what you currently get. ThxOliver Hader

2 Answers

0
votes

You could either go the tidyverse way using tidyr::gather() or coerce your dataframe to matrix before converting it to ts object.

I will let someone else elaborate on how to melt a dataframe, here's a suggestion of the second, base R approach.

Your data:

set.seed(12)
dfm <- matrix(round(rnorm(38*12), digits = 2),
                                 nrow = 38, ncol = 12)
colnames(dfm) <- month.abb
df<- data.frame(Year=seq(1980, 2017), dfm)

First I suggest you remove Year variable and put it into the row names:

rownames(df)<-df$Year
df$Year <- NULL

#head(df)

Then you can coerce your dataframe to matrix. Watch out for direction of the matrix - you will have to transpose it before interpreting it as vector.

df_ts <- ts(as.vector(t(as.matrix(df))), 
   start=c(1980,1), end=c(2017,12), frequency=12)

Now you have your ts object which you can plot:

plot(df_ts)

ts

0
votes

Note that columns in your dataframe represents different things (mixing variables and observations) with different meanings. For example first column is year, whereas others are months. Therefore you have to tidy your dataframe first. Using example data above:

library(tidyr)
library(dplyr)

df_ts <- df %>% 
  gather(key=Month, value=Value, -Year) %>% 
  mutate(Month=factor(Month, levels = c("Jan", "Feb", "Mar", 
                                        "Apr", "May", "Jun", 
                                        "Jul", "Aug", "Sep", 
                                        "Oct", "Nov", "Dec"))) %>% 
  arrange(Year, Month) %>% 
  pull(Value) %>% 
  as.ts(start=c(1980,1), end=c(2017,12), frequency=12)