Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract / subset an element from a list with the magrittr %>% pipe?

Tags:

r

magrittr

Since the introduction of the %>% operator in the magrittr package (and it's use in dplyr), I have started to use this in my own work.

One simple operation has me stumped, however. Specifically, this is the extraction (or subsetting) of elements from a list.

An example: In base R I would use $, [ or [[ to extract an element from a list:

iris$Species iris[["Species"]] 

I can achieve the same using the %>% pipe:

iris %>%   subset(select = "Species") %>%   head    Species 1  setosa 2  setosa 3  setosa 4  setosa 5  setosa 6  setosa 

Or

iris %>%   `[[`("Species") %>%   levels  [1] "setosa"     "versicolor" "virginica"  

However, this feels like a messy, clunky solution.

Is there a more elegant, canonical way to extract an element from a list using the %>% pipe?

Note: I don't want any solution involving dplyr, for the simple reason that I want the solution to work with any R object, including lists and matrices, not just data frames.

like image 996
Andrie Avatar asked Nov 24 '14 08:11

Andrie


People also ask

How do I extract the first sub element from a list in R?

To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).

What is Magrittr package in R?

The magrittr package offers a set of operators which make your code more readable by: structuring sequences of data operations left-to-right (as opposed to from the inside and out), avoiding nested function calls, minimizing the need for local variables and function definitions, and.


1 Answers

Use use_series, extract2 and extract for $, [[, [, respectively.

?extract 

magrittr provides a series of aliases which can be more pleasant to use when composing chains using the %>% operator."

For your example, you could try

iris %>%   extract("Species") 

and

iris %>%   extract2("Species") %>%   levels 

See the bottom of this page for more: http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

like image 72
Bangyou Avatar answered Sep 29 '22 03:09

Bangyou