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

如何用R语言生成i、Xs、Vs、Gs层级组合的乘积结果表格?

Solution in R

Alright, let's tackle this problem step by step. The goal is to create 27 unique cross-category combinations (3×3×3) of one X, one V, one G variable plus the "i" variable, then calculate the column-wise product for each combination. Here's how to do it in both base R and tidyverse styles:

Base R Approach

First, let's start with your raw data, then walk through each step:

  1. Construct the original dataset (as you provided):
variable <- c("i","x1","x2","x3","v1","v2","v3","g1","g2","g3")
df <- data.frame(replicate(10, sample(0:100, 10, rep=TRUE)))
df$var <- variable
  1. Reshape the data for easy access
    We need to index rows by the var values, so we'll set var as the row names to simplify lookup:
# Convert to a data frame with row names matching the var column
df_wide <- df
rownames(df_wide) <- df_wide$var
df_wide$var <- NULL  # Remove the now-redundant var column
  1. Generate valid cross-category combinations
    We'll use expand.grid to create all valid combinations (i + 1 X + 1 V + 1 G) — this ensures we never get same-category multiples:
# Define each category's variables
x_group <- c("x1", "x2", "x3")
v_group <- c("v1", "v2", "v3")
g_group <- c("g1", "g2", "g3")

# Create all 3×3×3 = 27 combinations
combinations <- expand.grid(
  i = "i",
  x = x_group,
  v = v_group,
  g = g_group,
  stringsAsFactors = FALSE
)

# Add a readable group label (optional but helpful for debugging)
combinations$group_label <- apply(combinations, 1, paste, collapse = ",")
  1. Calculate column-wise products
    We'll write a helper function to compute the product for a given combination, then apply it to all rows:
# Helper function to compute the product of 4 selected rows
compute_product_row <- function(i_val, x_val, v_val, g_val, data) {
  # Extract the four rows corresponding to the combination
  i_row <- data[i_val, ]
  x_row <- data[x_val, ]
  v_row <- data[v_val, ]
  g_row <- data[g_val, ]
  
  # Calculate the product for each column
  return(mapply(function(a, b, c, d) a * b * c * d, i_row, x_row, v_row, g_row))
}

# Apply the function to every combination
product_matrix <- do.call(rbind, lapply(1:nrow(combinations), function(idx) {
  combo <- combinations[idx, ]
  compute_product_row(combo$i, combo$x, combo$v, combo$g, df_wide)
}))

# Combine combinations with product results into a final data frame
final_df <- cbind(combinations, as.data.frame(product_matrix))

Tidyverse Approach (Using dplyr + tidyr)

If you prefer a more concise, pipe-based workflow:

library(tidyverse)

# Original data
variable <- c("i","x1","x2","x3","v1","v2","v3","g1","g2","g3")
df <- data.frame(replicate(10, sample(0:100, 10, rep=TRUE))) %>%
  mutate(var = variable)

# Reshape to row names matching the var column
df_wide <- df %>% column_to_rownames("var")

# Generate combinations and compute products in one streamlined pipe
final_df <- expand_grid(
  i = "i",
  x = str_subset(variable, "^x"),  # Auto-select all X variables
  v = str_subset(variable, "^v"),  # Auto-select all V variables
  g = str_subset(variable, "^g")   # Auto-select all G variables
) %>%
  mutate(group_label = str_c(i, x, v, g, sep = ",")) %>%
  rowwise() %>%
  mutate(
    # Calculate product row as a list column
    product_row = list(df_wide[i,] * df_wide[x,] * df_wide[v,] * df_wide[g,])
  ) %>%
  unnest_wider(product_row)  # Expand list column into individual product columns

Key Notes

  • Valid Combinations: Both methods ensure we only get cross-category pairs (no duplicates from the same group) by explicitly selecting one variable from each category.
  • Column-wise Product: Each column in the final output is the product of the corresponding columns from the four selected rows (e.g., X1 = i's X1 × x1's X1 × v1's X1 × g1's X1).
  • Flexibility: The tidyverse version auto-selects variables by their prefix, so if you add more X/V/G variables later, you won't need to update the code manually.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:48:47