简体   繁体   中英

Covert list to data.frame in R

I have list of data with varying list length:

[[1]]
[1] "2009" "2010" "2011" "2012"

[[2]]
[1] "2010" "2011" "2012" "2013"

[[3]]
[1] "2008" "2009" "2010" "2011" "2012"

[[4]]
[1] "2011" "2012"

I would like to get one column data.frame like this:

2009
2010
2011
2012
2010
2011
....

I went on doing this unsuccessfully:

# transpose list of years  
YearsDf <- lapply(GetYears, data.frame)

Remove colnames (since the list of dataframes gave some weird column names):

YearsOk <- lapply(YearsDf, function(x) "colnames<-"(x, NULL))

All this comes to:

 [[1]]
   NA
1 2009
2 2010
3 2011
4 2012

 [[2]]
   NA
1 2010
2 2011
3 2012
4 2013

......

Now just bind and get data.frame. This gave NA's

ldply(YearsOk, data.frame)

How I get to the data.frame of one column?

Did you consider unlist ?

myL <- list(as.character(2009:2012), 
            as.character(2010:2011), 
            as.character(2009:2014))
data.frame(year = unlist(myL))
#    year
# 1  2009
# 2  2010
# 3  2011
# 4  2012
# 5  2010
# 6  2011
# 7  2009
# 8  2010
# 9  2011
# 10 2012
# 11 2013
# 12 2014

If you think it will be important for you to retain which list element the value came from, consider stack (which requires a named list) or melt from the "reshape2" package:

library(reshape2)
melt(myL)
#    value L1
# 1   2009  1
# 2   2010  1
# ...SNIP...
# 11  2013  3
# 12  2014  3

## stack requires names, so add some in...
stack(setNames(myL, seq_along(myL)))
#    values ind
# 1    2009   1
# 2    2010   1
# ...SNIP...
# 12   2014   3

Finally, this is absolutely not the approach I would take, but based on your example code, perhaps you were trying to do something like:

do.call(rbind, lapply(myL, function(x) data.frame(year = x)))

It's quite simple. This answer gets for different length

Q<-list(a=a,b=b)
str(Q)
List of 2
 $ a: int [1:11] 1 2 3 4 5 6 7 8 9 10 ...
 $ b: int [1:29] 2 3 4 5 6 7 8 9 10 11 ...
Q$a
 [1]  1  2  3  4  5  6  7  8  9 10 11
T<-c(Q$a,Q$b)
T
 [1]  1  2  3  4  5  6  7  8  9 10 11  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17
[28] 18 19 20 21 22 23 24 25 26 27 28 29 30
TT<-data.frame(T)
TT
    T
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10
11 11
12  2
13  3
14  4
15  5
16  6
17  7
18  8
19  9
20 10
21 11
22 12
23 13
24 14
25 15
26 16
27 17
28 18
29 19
30 20
31 21
32 22
33 23
34 24
35 25
36 26
37 27
38 28
39 29
40 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM