Search code examples
rdplyrpurrrmagrittr

How to extract a single element of list-value of function using dplyr/magrittr - R


I'm writing code using dplyr and pipes and using NbClust function, which returns a list of objects named All.index, All.CriticalValues, Best.nc, Best.partition.

So I can assign my expression to some variable and then refer to Best.nc element as a variable$Best.nc. But how can I extract Best.nc element using pipes?

I have tried purrr::map('[[', 'Best.nc') but it didn't work.


Solution

  • You can directly use the base R [[ as a function without map:

    lst <- list(a = 1, b = 2)
    
    lst %>% `[[`('a')
    # [1] 1
    
    variable %>% `[[`('Best.nc')
    

    Or with purrr, you can use the pluck function and simply provide the element index or name:

    library(purrr)
    
    lst %>% pluck('a')
    # [1] 1
    lst %>% pluck(1)
    # [1] 1
    

    For your case:

    variable %>% pluck('Best.nc')
    

    The advantage of pluck to [[ extractor is that you can index deeply for a nested list, for instance:

    lst <- list(a = list(x = list(), y = 'm', z = 1:3), b = 2)
    

    To access the z element nested in a:

    lst %>% pluck('a', 'z')
    # [1] 1 2 3