在R中对Iris数据集列循环执行Dunn检验时列名获取失败的问题排查
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

