Kent Orr
Kent Orr

Reputation: 504

Using .data pronoun twice in lapply optional arguments

I would like to use a lapply function that passes the list item to two arguments in FUN.

For example, given that:

> lapply(state.abb, paste, c(.data, 2))
[[1]]
[1] "AL 2"

[[2]]
[1] "AK 2"

Here I can pass the list argument .data and 2 to the paste function. But in my application I want to pass .data to both paste arguments. In my imagination this would be the code and output:

>lapply(state.abb, paste, c(.data, .data))
[[1]]
[1] "AL AL"

[[2]]
[1] "AK AK"

But what I get instead is

> lapply(state.abb, paste, c(.data, .data))
[[1]]
[1] "AL "

[[2]]
[1] "AK "

I can in this instance supply state.abb again, but in my actual use case this is part of a much larger data set and I'm trying to avoid naming objects as much as possible.

Help much appreciated!

Upvotes: 0

Views: 52

Answers (3)

MrFlick
MrFlick

Reputation: 206232

The .data pronoun is a tidyverse (dplyr/ggplot2) thing. It does not work with base functions like lapply. (in fact if you ran that code without loading dplyr or ggplot2 you should get an "object not found" error). The .data basically defined to be just an empty list if any other functions use it so it's not doing anything for you. So these are all the exact same

lapply(state.abb, paste, c(.data, 2))
lapply(state.abb, paste, c(list(), 2))
lapply(state.abb, paste, list(2))

If you want to use the same parameter multiple times with lapply, then you would need to write your own function

lapply(state.abb, function(x) paste(x, x))

or you could use the purrr::map function and use .x for the data with the formula syntax for your function

purrr::map(state.abb, ~paste(.x, .x))

Upvotes: 1

MarBlo
MarBlo

Reputation: 4524

Not neccessarily a better solution than the ones above, but another:

Map(function(state.abb, i) paste(i, state.abb), state.abb, state.abb)

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You can use an anonymous function :

lapply(state.abb, function(x) paste(x, x))

OR paste and then make it a list.

as.list(paste(state.abb, state.abb))

Upvotes: 0

Related Questions