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

寻求可枚举指定边际的3x3表格的R函数,支持指定行列边际参数

Enumerate All 3x3 Tables with Specified Margins in R

Got it, here's a tailored R function that generates every valid 3x3 contingency table matching your input row and column margins. It works by leveraging the structure of 3x3 tables—once you fix the top-left 2x2 elements, the rest are determined by the margin constraints, so we just need to validate that all derived values are non-negative integers (since these tables represent counts).

f <- function(rowMargins, colMargins) {
  # Check if total sums match (no solution otherwise)
  if (sum(rowMargins) != sum(colMargins)) {
    message("Row and column totals don't match—no valid tables.")
    return(list())
  }
  
  total <- sum(rowMargins)
  tables <- list()
  table_idx <- 1
  
  # Iterate over possible values for first row, first column (a)
  for (a in 0:min(rowMargins[1], colMargins[1])) {
    # Remaining in first row after a
    rem_row1 <- rowMargins[1] - a
    # Remaining in first column after a
    rem_col1 <- colMargins[1] - a
    
    # Iterate over possible values for first row, second column (b)
    for (b in 0:min(rem_row1, colMargins[2])) {
      r1c3 <- rem_row1 - b
      # Check if third element of first row is non-negative and fits column 3 margin
      if (r1c3 < 0 || r1c3 > colMargins[3]) next
      
      rem_col2 <- colMargins[2] - b
      
      # Iterate over possible values for second row, first column (c)
      for (c in 0:min(rowMargins[2], rem_col1)) {
        rem_row2 <- rowMargins[2] - c
        rem_col1_after_c <- rem_col1 - c
        
        # Iterate over possible values for second row, second column (d)
        for (d in 0:min(rem_row2, rem_col2)) {
          r2c3 <- rem_row2 - d
          # Check if third element of second row is non-negative and fits remaining column 3 margin
          if (r2c3 < 0 || (r1c3 + r2c3) > colMargins[3]) next
          
          # Calculate third row elements
          r3c1 <- rem_col1_after_c
          r3c2 <- rem_col2 - d
          r3c3 <- rowMargins[3] - r3c1 - r3c2
          
          # Final checks: all third row elements non-negative, and r3c3 matches column 3 margin
          if (r3c1 >= 0 && r3c2 >= 0 && r3c3 >= 0 && (r1c3 + r2c3 + r3c3) == colMargins[3]) {
            # Build the table
            current_table <- matrix(
              c(a, b, r1c3,
                c, d, r2c3,
                r3c1, r3c2, r3c3),
              nrow = 3, byrow = TRUE
            )
            tables[[table_idx]] <- current_table
            table_idx <- table_idx + 1
          }
        }
      }
    }
  }
  
  if (length(tables) == 0) {
    message("No valid tables found for the given margins.")
  }
  
  tables
}

How It Works

  • Initial Check: First, we verify that the total sum of row margins equals the total sum of column margins—if not, there's no way to create a valid table, so we return an empty list.
  • Nested Loops: We iterate over all feasible values for the top-left 2x2 elements (a, b, c, d), ensuring each value doesn't exceed its respective row/column margin and leaves room for non-negative remaining elements.
  • Derive & Validate: For each combination of the 2x2 elements, we calculate the remaining 5 elements using the margin constraints. We then check that all elements are non-negative and that the bottom-right element is consistent across both row and column totals.
  • Collect Results: Valid tables are stored in a list, which is returned at the end.

Example Usage

Let's test it with your sample input:

# Generate all tables for the given margins
result <- f(rowMargins=c(3,10,2), colMargins=c(4,8,3))

# Print the first few tables to verify
for (i in 1:length(result)) {
  cat("Table", i, ":\n")
  print(result[[i]])
  cat("\n")
}

This will output every 3x3 table where:

  • Row sums are [3, 10, 2]
  • Column sums are [4, 8, 3]

Notes

  • This function assumes your margins are non-negative integers (standard for contingency tables). If you need to handle non-integer values, you'll need to adjust the validation checks.
  • For larger tables (bigger than 3x3), this nested loop approach becomes inefficient, but it's perfect for the 3x3 case you're targeting.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:28:26