Olivia
Olivia

Reputation: 41

convert List to a dataframe in R

I have created 100 random time series with these code

set.seed(1023172)
t<- seq(from=1,to=100,by=1)+10+rnorm(100,sd=7)
lst1 <- lapply(asplit(as.matrix(t), 1), ts, start = 2000, end = 2009)
print(lst1)

Then I want to convert this lst1 from a list to a data frame. The list looks partly like this:

[[1]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 7.791329 7.791329 7.791329 7.791329 7.791329 7.791329 7.791329 7.791329
 [9] 7.791329 7.791329

[[2]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 6.355925 6.355925 6.355925 6.355925 6.355925 6.355925 6.355925 6.355925
 [9] 6.355925 6.355925

[[3]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 8.250623 8.250623 8.250623 8.250623 8.250623 8.250623 8.250623 8.250623
 [9] 8.250623 8.250623

[[4]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 15.20932 15.20932 15.20932 15.20932 15.20932 15.20932 15.20932 15.20932
 [9] 15.20932 15.20932

[[5]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 19.12282 19.12282 19.12282 19.12282 19.12282 19.12282 19.12282 19.12282
 [9] 19.12282 19.12282

[[6]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 14.01422 14.01422 14.01422 14.01422 14.01422 14.01422 14.01422 14.01422
 [9] 14.01422 14.01422

[[7]]
Time Series:
Start = 2000 
End = 2009 
Frequency = 1 
 [1] 10.38471 10.38471 10.38471 10.38471 10.38471 10.38471 10.38471 10.38471
 [9] 10.38471 10.38471

I have tried df <- data.frame(matrix(unlist(lst1), ncol = max(lengths(lst1)), byrow = TRUE)), but the data type is always list. Can anybody help?

Edited on 17.08-- the ultimate goal is to be able to fit dcc.garch on this dataset so it it better to look like:

year ts1 ts2 ts3 ts4
2000 1 2 3 4

Upvotes: 1

Views: 1248

Answers (2)

Susan Switzer
Susan Switzer

Reputation: 1922

Have you tried as.data.frame()?

set.seed(1023172)
t<- seq(from=1,to=100,by=1)+10+rnorm(100,sd=7)
lst1 <- lapply(asplit(as.matrix(t), 1), ts, start = 2000, end = 2009)
df <- as.data.frame(lst1)

Upvotes: 1

akrun
akrun

Reputation: 887118

If we need to convert, perhaps, use as_tsibble from tsibble

library(tsibble)
out <-  lapply(head(lst1), as_tsibble)

-ouptut

> head(out, 3)
[[1]]
# A tsibble: 10 x 2 [1Y]
   index value
   <dbl> <dbl>
 1  2000  7.79
 2  2001  7.79
 3  2002  7.79
 4  2003  7.79
 5  2004  7.79
 6  2005  7.79
 7  2006  7.79
 8  2007  7.79
 9  2008  7.79
10  2009  7.79

[[2]]
# A tsibble: 10 x 2 [1Y]
   index value
   <dbl> <dbl>
 1  2000  6.36
 2  2001  6.36
 3  2002  6.36
 4  2003  6.36
 5  2004  6.36
 6  2005  6.36
 7  2006  6.36
 8  2007  6.36
 9  2008  6.36
10  2009  6.36

[[3]]
# A tsibble: 10 x 2 [1Y]
   index value
   <dbl> <dbl>
 1  2000  8.25
 2  2001  8.25
 3  2002  8.25
 4  2003  8.25
 5  2004  8.25
 6  2005  8.25
 7  2006  8.25
 8  2007  8.25
 9  2008  8.25
10  2009  8.25

Upvotes: 2

Related Questions