1

I have a list output that looks like this snippet:

[[1]]
[1] 109

[[2]]
integer(0)

[[3]]
[1] 80

Is there a way to transform it into this format?

C1   C2
1    109
2    0 (or NA)
3    80

Not sure where to even start... If I unlist it I noticed that I lose my integer(0) positions, which are important for me to keep.

lmo
  • 37,904
  • 9
  • 56
  • 69
val
  • 1,629
  • 1
  • 30
  • 56
  • Possible duplicate of http://stackoverflow.com/questions/17388096/convert-list-with-null-entres-to-data-frame-in-r – akrun Mar 02 '17 at 05:34

3 Answers3

5

With as.numeric you can retain integer(0) as NA.

data.frame(C1 = seq(length(lst)), C2 = as.numeric(lst))

#  C1  C2
#1  1 109
#2  2  NA
#3  3  80
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

Kind of

L = list(109,integer(0),80)
sapply(L, '[', 1:1) #OR sapply(L, function(a) a[1])
#[1] 109  NA  80

#If you need a data.frame

data.frame(cbind(1:length(L),lapply(L, '[', 1:1)))
#  X1  X2
#1  1 109
#2  2  NA
#3  3  80
d.b
  • 32,245
  • 6
  • 36
  • 77
1

We can do this using stack

stack(setNames(lapply(lst, `length<-`, 1), seq_along(lst)))[2:1]
akrun
  • 874,273
  • 37
  • 540
  • 662