-2

I have the following elements in a list and I want to collapse them into a data frame where only the same columns across the list are retained.

I tried the following but it doesn't give me exactly what I want. Since it just NAs the columns that aren't in the other element. I would be even better to be able to choose which columns to collapse on.

n.obs <- sapply(lst, length)
seq.max <- seq_len(max(n.obs))
mat <- t(sapply(lst, "[", i = seq.max))




lst[[1]]
$id
[1] "akromils-production"

$name
[1] "Akro-Mils Production"

$month
[1] 12000

$year
[1] 137000

$units
[1] 3000

$clients
[1] 6

$pbox
[1] FALSE

$punits
[1] 0

$cbox
[1] FALSE

$cunits
[1] 0

$sbox
[1] FALSE

$sunits
[1] 0

$eval
[1] FALSE

$public
[1] FALSE

lst[[2]]
$id
[1] "adc-production-2"

$name
[1] "American Diagnostics - Production (2)"

$month
[1] 26000

$year
[1] 312000

$units
[1] 650

$clients
[1] 2

$pbox
[1] TRUE

$punits
[1] 650

$eval
[1] FALSE

$public
[1] FALSE
Hillary
  • 785
  • 1
  • 6
  • 17
  • In order to make your question more reproducible could you please provide `lst`and `seq.max`? E.g. `dput(lst)`, and if `seq.max` is a function, which package? – jay.sf May 09 '19 at 20:23

1 Answers1

0

As stated in the comments you should always provide reproducible sample data and code. Minimal sample data is best provided with dput, which avoids us having to manually type out your data, and also avoids ambiguities due to unknown/ambiguous data types. You've been around SO for a while, so you should know how to post good questions.

In response to your question, one option would be to use dplyr::bind_rows and dplyr::bind_cols and then select only those columns that don't contain any NAs.

library(tidyverse)
bind_rows(map(lst, bind_cols)) %>% select_if(~!any(is.na(.x)))
## A tibble: 2 x 10
#  id         name           month   year units clients pbox  punits eval  public
#  <chr>      <chr>          <dbl>  <dbl> <dbl>   <dbl> <lgl>  <dbl> <lgl> <lgl>
#1 akromils-… Akro-Mils Pro… 12000 137000  3000       6 FALSE      0 FALSE FALSE
#2 adc-produ… American Diag… 26000 312000   650       2 TRUE     650 FALSE FALSE

Sample data

lst <- list(
    list(
        id = "akromils-production",
        name = "Akro-Mils Production",
        month = 12000,
        year = 137000,
        units = 3000,
        clients = 6,
        pbox = FALSE,
        punits = 0,
        cbox = FALSE,
        cunits = 0,
        sbox = FALSE,
        sunits = 0,
        eval = FALSE,
        public = FALSE),
    list(
        id = "adc-production-2",
        name = "American Diagnostics - Production (2)",
        month = 26000,
        year = 312000,
        units = 650,
        clients = 2,
        pbox = TRUE,
        punits = 650,
        eval = FALSE,
        public = FALSE)
)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68