0

I want to convert a list that has a list of numbers of varying lengths(1-4) for the values into an mx4 dataframe with NAs in place of missing values.

So far I was only able to row bind using: do.call(rbind, lapply(list, data.frame))

Gabriella
  • 312
  • 2
  • 11
  • 1
    Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557/3358272 (and https://xkcd.com/2116/). Please just include the code or data (e.g., `dput(head(x))` or `data.frame(...)`) directly. – r2evans Jan 13 '20 at 22:25
  • 1
    You should provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) instead of posting picture of your dataframe. – M-- Jan 13 '20 at 22:25
  • Try with `do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))` – akrun Jan 13 '20 at 22:28
  • 1
    Okay sorry, I am working with sensitive data so I will have to make a reproducible example. Thanks for letting me know! – Gabriella Jan 13 '20 at 22:29
  • Sensitive data is a "normal thing" :-), but you'll find many people rankle a little when you ask us to transcribe data for you. This was a small example, certainly, but the premise is a little frustrating. – r2evans Jan 13 '20 at 22:31

1 Answers1

1

You were close:

dat <- list(
  x = c(0.9, 0.5, 0.6, 0.8),
  y = c(0.5, 0.1),
  z = c(0.3, 0.2, 0.5)
)
as.data.frame(do.call(rbind, lapply(dat, `length<-`, max(lengths(dat)))))
#    V1  V2  V3  V4
# x 0.9 0.5 0.6 0.8
# y 0.5 0.1  NA  NA
# z 0.3 0.2 0.5  NA

(If you really need names like 1num, then you can do it manually. I suggest against leading names with a number, though, as that'll require you to backtick your $ accessors.)

r2evans
  • 141,215
  • 6
  • 77
  • 149