Native vs magrittr pipe: pulling out nested table with `[[`

When working with nested tables within a table, if I wanted to pull one out, I would typically do something like the following in tidyverse:

my_tibble %>% slice(111) %>% pull(nested_column) %>% .[[1]]

That last element in the pipeline is neccessary because otherwise my item is in a one element-long list and I want the object out from the list. unlist doesn't work because it flattens out the data structure (often a tibble) within the nested column.

Now the problem is that if I convert this to a native pipe pipeline, |> .[[1]] produces the following error:
Error: function '[[' not supported in RHS call of a pipe

My shortcut is to create a function like first <- function(x) x.[[1]], but surely there is already a native way to do this.

I think you are asking for a general base r way to select the first item from a list, base::head(x,n=) can be used for this, and there is base::tail also

purrr::pluck() is a pipe-friendly alternative to double-bracket indexing.


my_tibble |> 
  pull(nested_column) |> 
1 Like

Thanks, pluck did it for me. I kept remembering hoist which is the wrong function, but not pluck.

For the record, base::head doesn't seem to work for this, unless I'm implementing it wrong. It does select the item from the list, but it is still returned as a one (or more) element list.

> tibble(A=list(tibble(a=1:2, b=3:4))) |> pull(A) |> head(1)
# still a list:
# A tibble: 2 × 2
      a     b
  <int> <int>
1     1     3
2     2     4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.