Skip to content

Instantly share code, notes, and snippets.

@ashenkin
Created July 28, 2016 11:04

Revisions

  1. ashenkin created this gist Jul 28, 2016.
    18 changes: 18 additions & 0 deletions set_dev_contrasts.r
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    contr.sum.keepnames <- function(...) {
    # make deviation contrasts that don't lose the names of the factors in the model results
    # from https://stackoverflow.com/questions/10808853/why-does-changing-contrast-type-change-row-labels-in-r-lm-summary
    conS <- contr.sum(...)
    colnames(conS) = rownames(conS)[-length(rownames(conS))]
    conS
    }

    set_dev_contrasts <- function(df, colname = "site") {
    # Set contrasts to "deviation coding" so site effects are as compared to overall mean across all sites. I.e., sites together should have a mean 0 effect.
    # See http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm
    # Usage: my_df = set_dev_contrasts(my_df, colname = "col_to_set")
    col2setup = df[,colname]
    col2setup = as.factor(col2setup)[, drop = TRUE]
    contrasts(col2setup) <- contr.sum.keepnames(levels(col2setup))
    df[,colname] = col2setup
    return(df)
    }