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

在R中批量应用GoodmanKruskalGamma函数及配对列计算问询

Solution for Paired Goodman-Kruskal Gamma Calculation Between Item and Restscore Columns

Got it, let's sort out this paired calculation task! You already cracked batch processing with totalscore using magicfor, so adapting that to pair each itemX column with its corresponding restscoreX is straightforward once you align the column names properly. Here's a step-by-step breakdown:

Step 1: Prep Your Column Names

First, we need to get a list of all your item columns, then generate their matching restscore column names automatically (no manual typing needed!):

# Load required packages
library(magicfor)
library(DescTools) # Required for GoodmanKruskalGamma

# Extract all item column names (adjust the regex if your naming is different)
item_cols <- grep("^item", names(mydata), value = TRUE)
# Generate corresponding restscore column names
restscore_cols <- gsub("^item", "restscore", item_cols)

Step 2: Batch Paired Calculation with magicfor

Now use magicfor to loop through each paired column set and run the Gamma calculation:

# Initialize magicfor to capture results
magicfor(print, silent = FALSE)

# Loop through each paired column index
for (i in seq_along(item_cols)) {
  # Pull the current item and restscore columns from your data frame
  current_item <- mydata[[item_cols[i]]]
  current_restscore <- mydata[[restscore_cols[i]]]
  
  # Run the Goodman-Kruskal Gamma calculation
  GoodmanKruskalGamma(current_item, current_restscore, conf.level = 0.95)
}

# Store all results in a named list for easy reference
gamma_results <- magicresult()
names(gamma_results) <- item_cols # Name each result after its item column

Alternative: Use purrr for Functional Programming

If you prefer a tidyverse-style approach without magicfor, purrr::map2 works great for paired iterations:

library(purrr)

# Map over paired column names to run calculations
gamma_results <- map2(
  .x = item_cols,
  .y = restscore_cols,
  ~ GoodmanKruskalGamma(mydata[[.x]], mydata[[.y]], conf.level = 0.95)
)

# Name the results list
names(gamma_results) <- item_cols

Why Your Nested Loop Might Have Failed

Chances are the nested loop didn't work because you weren't explicitly pairing each item column with its exact restscore counterpart. By generating the column name pairs first, we eliminate any mismatch and keep the logic clean.

内容的提问来源于stack exchange,提问作者Pedro Henrique Ribeiro Santiag

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:53:04