You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用dplyr与purrr构建基于谓词的列表列集合跟踪列

Solution to Track Dynamic Item Sets with dplyr and purrr

Here's a straightforward approach to build your desired "set" column by combining purrr::accumulate() with set operations, grouped by user:

Step 1: Load Libraries and Define Input Data

First, let's set up our input dataframe (using tibble instead of data_frame as it's the modern dplyr equivalent):

library(dplyr)
library(purrr)

input_df <- tibble(
  user = c("1", "1", "1", "1"),
  item = c("a", "b", "a", "a"),
  include = c(TRUE, TRUE, FALSE, TRUE)
)

Step 2: Build the Dynamic Set Column

We'll group by user, then use accumulate() to iteratively update the set based on the include flag:

output_df <- input_df %>%
  group_by(user) %>%
  mutate(
    set = accumulate(
      .x = seq(n()),  # Iterate over row indices
      .f = function(current_set, row_idx) {
        # Add or remove the item based on the include flag
        if (include[row_idx]) {
          union(current_set, item[row_idx])
        } else {
          setdiff(current_set, item[row_idx])
        }
      },
      .init = character(0)  # Start with an empty set
    ) %>% tail(-1)  # Drop the initial empty set from the result
  ) %>%
  ungroup() %>%
  select(user, set)  # Keep only the desired columns

Step 3: Verify the Output

Let's confirm the result matches your expected structure:

print(output_df)
#> # A tibble: 4 × 2
#>   user  set      
#>   <chr> <list>   
#> 1 1     <chr [1]>
#> 2 1     <chr [2]>
#> 3 1     <chr [1]>
#> 4 1     <chr [2]>

# Inspect the contents of each set:
output_df$set
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [1] "a" "b"
#> 
#> [[3]]
#> [1] "b"
#> 
#> [[4]]
#> [1] "a" "b"

Key Notes

  • User-Specific Tracking: This solution works for multiple users—each user's set is updated independently of others.
  • Set Integrity: union ensures no duplicate items in the set, even if an item is added multiple times. setdiff safely removes items (and leaves the set unchanged if the item isn't present).
  • Flexibility: Adjust the logic easily if you need different behavior (e.g., allow duplicates by using c() instead of union, though that would make it a list rather than a strict set).

内容的提问来源于stack exchange,提问作者Matthew Emery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:59:36