Search code examples
rlmcontrast

Passing a list of contrasts read as characters to a linear mode in R


Probably missing something basic here.

I have XY data to which I want to fit an lm in R:

set.seed(1)
df <- data.frame(x = c("0h","0h","4h","4h","8h","8h","10h","10h"),
                 y = rnorm(8))

Fitting the lm is part of a function that receives as input the df and also the type of contrast that should be set. The contrast is read as a user input and hence is a character.

For example:

my.contrast <- "contr.helmert(4)"

I then want to pas this to contrast a model.matrix with which the lm will then be fitted.

I'm trying:

contrast.list <- list(x = my.contrast)
design.mat <- model.matrix(y ~ x, data = df, contrasts.arg = contrast.list)

But obviously getting the error:

Error in get(ctr, mode = "function", envir = parent.frame()) : 
  object 'contr.helmert(4)' of mode 'function' was not found

However, it's not clear to me what type I should convert my.contrast to for the model.matrix to work.

Obviously,

model.matrix(y ~ x, data = df, contrasts.arg = list(x = contr.helmert(4)))

Works fine


Solution

  • You may want to try with eval

    model.matrix(y ~ x, data = df, contrasts.arg = eval(parse(text=my.contrast)))
      (Intercept) x10h x4h x8h
    1           1    0   0   0
    2           1    0   0   0
    3           1    0   1   0
    4           1    0   1   0
    5           1    0   0   1
    6           1    0   0   1
    7           1    1   0   0
    8           1    1   0   0
    attr(,"assign")
    [1] 0 1 1 1
    attr(,"contrasts")
    attr(,"contrasts")$`x`
    [1] "contr.treatment"