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
  • 36,904
  • 9
  • 50
  • 61
val
  • 1,519
  • 1
  • 24
  • 49
  • 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
  • 355,584
  • 18
  • 123
  • 178
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
  • 31,615
  • 5
  • 30
  • 71
1

We can do this using stack

stack(setNames(lapply(lst, `length<-`, 1), seq_along(lst)))[2:1]
akrun
  • 789,025
  • 32
  • 460
  • 575