Manuel Pellicer
Manuel Pellicer

Reputation: 36

What does the `[` argument mean inside map_df?

I've come up with the following way of creating a data frame in R using the purrr package:

map_df(list, `[`, c("name_1", "name_2"))

while I had done it previously with

list %>% map_df(~data.frame(name_1 = .x[["name_1"]], name_2 =.x[["name_2"]]))

Would anyone explain the [ argument or guide me to a resource I could use Thanks

I have already checked out the https://purrr.tidyverse.org/reference/map.html, I haven't found anything useful, though. list is a generic list containing n elements, and each of this elements contains name_1 and name_2 elements which will be the colums of my n rows data frame.

Upvotes: 2

Views: 437

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

`[` is the subsetting operator. You’ll normally encounter it written like this:

x[index]

However, in R every operator is a function, and `[` is no different. To invoke an operator as a normal function, you need to backtick-quote it because otherwise R thinks that it should be surrounded by operands. For instance:

1 + 1 # is the same as
`+`(1, 1)

2 == 3 # is the same as
`==`(2, 3)

For subsetting operators, the rule is slightly different: they are invoked with opening-and-closing brackets but the operator name only has the opening brackets:

x[1, 2] # is the same as
`[`(x, 1, 2)

iris[['Species']] # is the same as
`[[`(iris, 'Species')

Now. Since `[` is a function (like all operators — see above), we can pass the function name into map_df like any other function. Think of the above as

map_df(list, extract, c("name_1", "name_2"))

Where extract would be defined as

extract = function (x, index) {
    x[index]
}

Or simply as:

extract = `[`

(In R you can assign functions to new names just like any other objects.)

Thanks to the way map_df handles formulas, the above is also identical to

map_df(list, ~ .x[.y], c("name_1", "name_2"))

Upvotes: 5

Related Questions