受Jennifer Bryan演讲启发转用tidyverse,首次使用pmap遇执行失败求助
pmap Code Isn't Working (and Fixes!) Hey there! Let's walk through what's going wrong with your tidyverse code and get it working right.
First, the Root Causes
Your code hits two main issues:
- Misusing
pmap:pmapis designed to work with lists (or data frames) where each element of the list corresponds to a separate argument for your function. You passedsample1(a 5-element character vector) directly, sopmaptries to pass 5 separate arguments to your single-parameter function—this is a mismatch that throws an error. - Comparing the whole tibble instead of a column:
prob == xchecks every value in the entireprobtibble againstx, but you only care about matching against thenamescolumn. That's not what you want, and it creates messy output even if it ran.
Fixes That Work
Since your goal is to check each value in sample1 against the names column in prob, here are two clean tidyverse approaches:
1. Use purrr::map (the right tool for single-vector iteration)
map is made exactly for iterating over a single vector and applying a function to each element. This is simpler and more appropriate than pmap here:
# Load packages library(tidyverse) # Create your data prob = tibble(names = letters[1:17]) sample1 = sample(letters, 5) # Working map approach map(sample1, ~ prob$names == .x)
The ~ creates a formula-style shortcut for your function, and .x refers to each element in sample1.
2. Wrap into a tibble for cleaner, tabular output
If you want to keep your sample values paired with their match results, use mutate with map:
tibble(sample_value = sample1) %>% mutate(match_results = map(sample_value, ~ prob$names == .x))
This gives you a tidy tibble where each row has a sample value and its corresponding logical vector of matches.
3. If you really want to use pmap (though map is better here)
If you're set on pmap, you need to wrap sample1 into a single-element list (so pmap treats each element of sample1 as the first (and only) argument to your function):
pmap(list(sample1), function(x) prob$names == x)
Again, this is overkill for your use case—map is the more intuitive choice here.
内容的提问来源于stack exchange,提问作者Karl Cottenie

