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

在R中基于现有data.table扩展网格(幂集)并添加prime后缀列

Solution

Got it, let's solve this using data.table's optimized tools—since we can't use raw data, we'll derive all prime column combinations directly from your filtered Vmat1, then do a cross join to pair every original row with every possible prime state. Here's the step-by-step approach:

  1. Build the prime combinations table from Vmat1's unique values
    First, we extract the unique values from each column in Vmat1 (since those are the only possible values we need for the prime columns), then generate all possible combinations of these values. We'll rename the columns to add the "prime" suffix as we go:
# Extract unique values per column, expand to all combinations, rename columns
prime_combs <- Vmat1[, lapply(.SD, unique)] %>%
  expand.grid(stringsAsFactors = FALSE) %>%
  setDT() %>%
  setnames(names(.), paste0(names(.), "prime"))
  1. Cross join Vmat1 with the prime combinations
    In data.table, a cross join (to get every possible pairing of rows from two tables) is easy with the on = .() syntax plus allow.cartesian = TRUE (since we know the cartesian product is intentional here):
# Cross join original table with prime combinations
result <- Vmat1[prime_combs, on = .(), allow.cartesian = TRUE]

Full working example

Let's run this with your sample data to confirm it matches your expected output:

library(data.table)
Vmat1 = data.table(expand.grid(c(list(d = 1:2, w = 1:(3)))))

# Create prime combinations
prime_combs <- Vmat1[, lapply(.SD, unique)] %>%
  expand.grid(stringsAsFactors = FALSE) %>%
  setDT() %>%
  setnames(names(.), paste0(names(.), "prime"))

# Generate final result
result <- Vmat1[prime_combs, on = .(), allow.cartesian = TRUE]

# View the output
print(result)

This will produce exactly the 36-row table you provided, with every original row paired with every possible combination of dprime and wprime.

Why this works for your use case

  • We're only using the filtered values from Vmat1, so we avoid the memory bloat of working with unfiltered raw data.
  • The approach scales seamlessly with more columns—just add more columns to Vmat1, and the code will automatically generate the corresponding *prime columns and their combinations.
  • data.table's cross join is optimized for speed and memory, which is crucial when dealing with larger datasets for Markov chain transitions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:57:18