Using the%>% protocol and the dotted (.) Notation

When using map on a nested data_frame, I don’t understand why the last two versions give an error, how should I use a period ( . )?

 library(tidyverse) # dummy data df <- tibble(id = rep(1:10, each = 10), val = runif(100)) df <- nest(df, -id) # works as expected map(df$data, min) df %>% .$data %>% map(., min) # gives an error df %>% map(.$data, min) # Error: Don't know how to index with object of type list at level 1 df %>% map(data, min) 
+8
r magrittr
source share
1 answer

The problem is not map , but how the pipe %>% deals with . . Consider the following examples (remember that / is a function of two arguments in R):

Simple piping:

 1 %>% `/`(2) 

It is equivalent to `/`(1, 2) or 1 / 2 and gives 0.5 .

Simple . use:

 1 %>% `/`(2, .) 

It is equivalent to `/`(2, 1) or 2 / 1 and gives 2 .

You can see that 1 no longer used as the first argument, but only as the second.

Other use:

However, this does not work if a subset . :

 list(a = 1) %>% `/`(.$a, 2) 
 Error in `/`(., .$a, 2) : operator needs one or two arguments 

We can see that . entered twice as the first argument and a subset of the second argument. An expression of type .$a sometimes referred to as a call to a nested function (in this case, the $ function is used inside the / function).

We use curly braces to avoid entering the first argument:

 list(a = 1) %>% { `/`(.$a, 2) } 

Gives 0.5 again.

Actual problem:

In fact, you are calling map(df, df$data, min) , not map(df$data, min) .

Decision:

Use curly braces:

 df %>% { map(.$data, min) } 

Also see the heading Use a point for secondary purposes in ?magrittr::`%>%` , which reads:

In particular, if the placeholder is used only in the call nested function, lhs will also be placed as the first argument! The reason for this is that in most use cases it gives the most readable code. For example, iris %>% subset(1:nrow(.) %% 2 == 0) equivalent to iris %>% subset(., 1:nrow(.) %% 2 == 0) , but is slightly more compact. It is possible to reverse this behavior by including rhs in curly braces. For example, 1:10 %>% {c(min(.), max(.))} Is equivalent to c(min(1:10), max(1:10)) .

+5
source share

All Articles