Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pipes within map() in R

Tags:

r

dplyr

purrr

I'm getting unexpected results when attempting to pipe inside map()

map(ls(), ~ . %>% get %>% dim)

returns the following message:

Functional sequence with the following components:

 1. get(.)
 2. dim(.)

Use 'functions' to extract the individual functions. 

I don't really know how functions() would get me the result I want.

Is there a way to do it with pipes and map?

Without using pipes,

map(ls(), ~ get(dim(.)))

, the result is what I would expect.

like image 741
vuzun Avatar asked Apr 17 '18 13:04

vuzun


People also ask

Why do we use %>% in R?

The compound assignment %<>% operator is used to update a value by first piping it into one or more expressions, and then assigning the result. For instance, let's say you want to transform the mpg variable in the mtcars data frame to a square root measurement.

Can you pipe in a function R?

The pipe operator is used when we have nested functions to use in R Programming. Where the result of one function becomes the argument for the next function. The pipe functions improve the efficiency as well as readability of code.

How does the %>% pipe work in R?

What does the pipe do? The pipe operator, written as %>% , has been a longstanding feature of the magrittr package for R. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps.

What does Magrittr do 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

. %>% get %>% dim is already a function so just omit the ~, i.e.

map(ls(), . %>% get %>% dim)

or:

ls() %>% map(. %>% get %>% dim)
like image 196
G. Grothendieck Avatar answered Sep 19 '22 12:09

G. Grothendieck