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

在R中对Iris数据集列循环执行Dunn检验时列名获取失败的问题排查

Fixing Your Dunn Test Loop for the Iris Dataset

Hey there! Let's break down why your code isn't running properly and get it working smoothly.

The Root Cause

The main issue lies in how you're referencing column names within the dunn_test() formula. Using get() inside the formula syntax doesn't play nicely with rstatix's tidyeval-based interface. The dunn_test() function expects formula terms it can resolve directly in the dataset, and get() fails to translate string column names into valid formula terms correctly in this context.

Fixed Code Options

Here are two working versions of your code, both addressing the formula reference problem:

Option 1: Using Tidyeval (sym() and !!)

This converts your string column names into symbols that the formula can interpret correctly:

library(rstatix)
data <- iris

# Predefine the group column name since it's always Species (no need to re-fetch it in the loop)
group_col <- colnames(data)[5]

for (i in seq(1:4)) {
  feature_col <- colnames(data)[i]
  # Convert string to symbol and unquote it for the formula
  dtest <- data %>% 
    dunn_test( !!sym(feature_col) ~ !!sym(group_col), p.adjust.method = "BH")
  print(dtest)
  print(paste("Completed test for feature:", feature_col))
}

Option 2: Using reformulate()

This function builds a formula directly from strings, which is often more straightforward for dynamic formula scenarios:

library(rstatix)
data <- iris

group_col <- colnames(data)[5]

for (i in seq(1:4)) {
  feature_col <- colnames(data)[i]
  # Dynamically construct the test formula
  test_formula <- reformulate(response = feature_col, termlabels = group_col)
  dtest <- data %>% 
    dunn_test(formula = test_formula, p.adjust.method = "BH")
  print(dtest)
  print(paste("Completed test for feature:", feature_col))
}

Quick Optimization Note

I moved the group column (Species) outside the loop since it never changes—this is just a small cleanup, not a fix for the core issue, but it makes the code a bit more efficient.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:12:51