0

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.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
jakes
  • 1,964
  • 3
  • 18
  • 50
  • You need [to provide a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – alistaire Jun 23 '18 at 14:41
  • Best guess without having any of your code or data is `variable %>% pluck("Best.nc")` – camille Jun 24 '18 at 17:18

1 Answers1

3

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 
Psidom
  • 209,562
  • 33
  • 339
  • 356