将读取为字符的对比列表传递给 R 中的线性模式
Passing a list of contrasts read as characters to a linear mode in R
这里可能缺少一些基本的东西。
我有 XY
数据,我想将 lm
放入 R:
set.seed(1)
df <- data.frame(x = c("0h","0h","4h","4h","8h","8h","10h","10h"),
y = rnorm(8))
拟合 lm
是接收 df
以及应设置的 contrast
类型作为输入的函数的一部分。 contrast
被读取为用户输入,因此是 character
.
例如:
my.contrast <- "contr.helmert(4)"
然后我想通过这个来对比 model.matrix
,然后 lm
将与之进行对比。
我正在尝试:
contrast.list <- list(x = my.contrast)
design.mat <- model.matrix(y ~ x, data = df, contrasts.arg = contrast.list)
但明显报错:
Error in get(ctr, mode = "function", envir = parent.frame()) :
object 'contr.helmert(4)' of mode 'function' was not found
但是,我不清楚我应该将 my.contrast
转换成什么类型才能让 model.matrix
工作。
显然,
model.matrix(y ~ x, data = df, contrasts.arg = list(x = contr.helmert(4)))
工作正常
您可能想尝试 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"
这里可能缺少一些基本的东西。
我有 XY
数据,我想将 lm
放入 R:
set.seed(1)
df <- data.frame(x = c("0h","0h","4h","4h","8h","8h","10h","10h"),
y = rnorm(8))
拟合 lm
是接收 df
以及应设置的 contrast
类型作为输入的函数的一部分。 contrast
被读取为用户输入,因此是 character
.
例如:
my.contrast <- "contr.helmert(4)"
然后我想通过这个来对比 model.matrix
,然后 lm
将与之进行对比。
我正在尝试:
contrast.list <- list(x = my.contrast)
design.mat <- model.matrix(y ~ x, data = df, contrasts.arg = contrast.list)
但明显报错:
Error in get(ctr, mode = "function", envir = parent.frame()) :
object 'contr.helmert(4)' of mode 'function' was not found
但是,我不清楚我应该将 my.contrast
转换成什么类型才能让 model.matrix
工作。
显然,
model.matrix(y ~ x, data = df, contrasts.arg = list(x = contr.helmert(4)))
工作正常
您可能想尝试 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"