Reputation: 549
How could I pipe a data frame consisting of a list of logical vectors and a list of character vectors to purrr::map2()
to subset the character vectors using the logical vectors?
My efforts work without pipes, but I'm not sure how to do it with pipes:
For example, using this data frame:
a_pair = tibble(mask = list(TRUE, c(FALSE, TRUE), TRUE, TRUE,
c(FALSE, FALSE, FALSE, TRUE), TRUE, TRUE, TRUE,
TRUE, c(FALSE, FALSE, FALSE, TRUE)),
strings = list(".", c("0.29966", "0.31145"), "0.48243",
"0.55122",
c("0.10099", "0.10142", "0.49873", "0.56246"),
"0.56246", "0.10127", "0.70687", "0.68338",
c("0.03365", "0.16895", "0.68338", "0.82954")))
This works:
library(purrr)
map2(a_pair$mask, a_pair$strings, function(logical, string) subset(string, logical))
But this (as suggested in a related question) doesn't:
a_pair %>% map2(., names(.), ~{subset(.y, .x)})
Error in subset.default(.y, .x) : 'subset' must be logical
Do I need to do some sort of unlisting, or reference the logical vectors in a different way?
Upvotes: 1
Views: 315
Reputation: 206243
You should use
library(dplyr)
a_pair %>% {map2(.$strings, .$mask, subset)}
Using {}
helps to prevent the data being automatically passed as the first parameter.
Or if you include the magrittr
library, you can do
library(magrittr)
a_pair %$% map2(strings, mask, subset)
Upvotes: 2