kassambara / rstatix

Pipe-friendly Framework for Basic Statistical Tests in R
https://rpkgs.datanovia.com/rstatix/
432 stars 51 forks source link

Nonconforming number of contrast coefficients #206

Open chenyangjjj opened 1 month ago

chenyangjjj commented 1 month ago

Hi, I am using emmeans_test for post-hoc analysis, But got the error like "Nonconforming number of contrast coefficients", The covariate(sex) variable have been transfomed to numeric variable. But It doesn't work and made me feel confused

pwc <- C1_domains_D_C %>%
  emmeans_test(EpisodicMemory ~ D_diagnoseOms,
               covariate = I_sex,p.adjust.method = "bonferroni")

And What is the way of perfomring multi covariates? covariates1 + covariates2; or c("covariates1","covariates2")?

Thanks!

fubin1999 commented 1 month ago

This seems a bug for rstatix.

I was working with glycome data and facing the same problem as you had. When setting "age" as the covariate, things went well. But when setting "sex" as the covariate, I got the same "Nonconforming number of contrast coefficients" error. After a few experiments I decide to use the emmeans package to perform the post-hoc test manually. Here is my solution for your reference:

> data
# A tibble: 693 × 5
   sample group sex     age log_value
   <chr>  <fct> <chr> <dbl>     <dbl>
 1 S1     HCC   M        67      14.5
 2 S10    CHB   F        51      13.3
 3 S100   CHB   M        32      13.4
 4 S101   CHB   M        44      13.3
 5 S102   HC    F        27      12.8
 6 S103   CHB   F        23      13.4
 7 S104   HCC   M        49      14.2
 8 S105   CHB   M        46      14.1
 9 S108   HCC   M        72      13.8
10 S109   HC    M        56      14.5
# ℹ 683 more rows

In my case, "log_value" is the dependent variable, "group" is the independent variable, "sex" and "age" are the covariates.

> ancova_result <- aov(log_value ~ group + sex + age, data = data)
> emms <- emmeans::emmeans(ancova_result, ~ group)
> pairwise_comparisons <- emmeans::contrast(emms, "pairwise", adjust = "tukey")
> as_tibble(pairwise_comparisons)
# A tibble: 6 × 6
  contrast  estimate     SE    df t.ratio    p.value
  <chr>        <dbl>  <dbl> <dbl>   <dbl>      <dbl>
1 HC - CHB    0.0328 0.0745   687   0.440 0.971     
2 HC - LC    -0.175  0.0760   687  -2.31  0.0973    
3 HC - HCC   -0.469  0.0702   687  -6.68  0         
4 CHB - LC   -0.208  0.0674   687  -3.09  0.0114    
5 CHB - HCC  -0.501  0.0600   687  -8.36  0         
6 LC - HCC   -0.293  0.0577   687  -5.08  0.00000287

If you have multiple dependent variables like I did (I had dozens of glycans to test), use nest from tidyr and compute the results sequentially in mutate with map, and finally unnest.

Hope you find it useful.