easystats / easystats/datawizard

Add function for Weighted Effect Coding?

Open
#363 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Feature idea :fire:
Dominant language
R
Stars
238
Forks
18
Avg merge
1d 15h
Merged PRs (30d)
4

Description

Is this something we can add here?
(After I built the function, I saw it was implemented in the {wec} package....)

contr.wsum <- function(x, ref, ...) {
  x <- as.factor(x)
  lvls <- levels(x)
  n <- nlevels(x)
  
  if (!missing(ref)) {
    if (!ref %in% lvls) stop("")
    lvls <- c(setdiff(lvls, ref), ref)
    x <- factor(x, levels = lvls)
  } else {
    ref <- lvls[n]
  }
  
  M <- contr.sum(n)
  rownames(M) <- lvls
  
  tab <- proportions(table(x))
  M[ref,] <- -unname(tab[-n] / tab[n])
  M
}

contr.wsum(mtcars$cyl)
#>         [,1] [,2]
#> 4  1.0000000  0.0
#> 6  0.0000000  1.0
#> 8 -0.7857143 -0.5

# same as:  
wec::contr.wec(factor(mtcars$cyl), "8")
#>            4    6
#> 1  1.0000000  0.0
#> 2  0.0000000  1.0
#> 3 -0.7857143 -0.5

Usage:

mtcars$cyl_f <- factor(mtcars$cyl)
contrasts(mtcars$cyl_f) <- contr.wsum(mtcars$cyl_f)
m <- lm(mpg ~ cyl_f, mtcars)
coef(m)[1]
#> (Intercept) 
#>    20.09062
mean(mtcars$mpg)
#> [1] 20.09062

Created on 2023-02-08 with reprex v2.0.2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue provides the proposed contr.wsum entry point and mtcars example; start by comparing its behavior with wec::contr.wec and checking how datawizard exposes similar R functions. Confirm whether this API belongs in datawizard, then define tests for the shown weighted contrasts and lm intercept behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
data
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.