Home > Software design >  How to use list sub-element names instead of actual sub-element name
How to use list sub-element names instead of actual sub-element name

Time:09-14

I have a list obtained through an API:

my_ls <- list(list(hs_legal_basis = list(value = "Freely given consent from contact"), 
hs_date_entered_lead = list(value = "1603393304662"), hs_email_last_send_date = list(
    value = "1663103935369")), list(hs_legal_basis = list(
value = "Legitimate interest – prospect/lead"), hs_date_entered_lead = list(
value = "1588624274359"), hs_email_last_send_date = list(
value = "1657120876426")), list(hs_legal_basis = list(value = "Freely given consent from contact"), 
hs_date_entered_lead = list(value = "1622833942763"), hs_email_last_send_date = list(
    value = "1601582035403")))

The awkward thing is that each element has the name of 'value'. When converting to a data frame using bind_rows the column names come through as 'value' in each case.

The column names I want for the actual values are the sublist names - from the above example these would be:

  • hs_legal_basis
  • hs_date_entered_lead OR
  • hs_email_last_send_date

How do I in effect replace the element name of 'value' with the parent sub-list name?

Ideally I'd like to use purrr functions to accomplish this.

Thanks.

CodePudding user response:

You can do:

library(purrr)

map_dfc(transpose(my_ls), unlist) 

# A tibble: 3 × 3
  hs_legal_basis                      hs_date_entered_lead hs_email_last_send_date
  <chr>                               <chr>                <chr>                  
1 Freely given consent from contact   1603393304662        1663103935369          
2 Legitimate interest – prospect/lead 1588624274359        1657120876426          
3 Freely given consent from contact   1622833942763        1601582035403          

CodePudding user response:

No idea about the purrr implementation, but here's a base R attempt after unlisting each sublist joined together with c():

data.frame(do.call(Map, c(\(...) unlist(c(...)), my_ls)))
#                       hs_legal_basis hs_date_entered_lead hs_email_last_send_date
#1   Freely given consent from contact        1603393304662           1663103935369
#2 Legitimate interest   prospect/lead        1588624274359           1657120876426
#3   Freely given consent from contact        1622833942763           1601582035403
  • Related