1

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?

pogibas
  • 27,303
  • 19
  • 84
  • 117
bheavner
  • 519
  • 1
  • 4
  • 20
  • 1
    Why do you want to do this in a pipe? The a_pair object shows up twice in the expression that works, so any pipe is going to have to be complicated. Pipes are great when the LHS is the first argument of the RHS, and okay when the LHS shows up once in the RHS, but they're unreadable when things get more complicated. – user2554330 Sep 15 '17 at 18:45
  • Honestly, I've got it working without, and that's okay for my immediate needs, so mostly because I'm curious how to do it with a pipe! – bheavner Sep 15 '17 at 18:48

1 Answers1

2

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)
MrFlick
  • 195,160
  • 17
  • 277
  • 295