1

我正在尝试根据存储在数组中的变量名称更新 R 中线性模型的公式。我substitute(为此使用),代码如下。

var = 'a'
covar = c('b', 'c')
covar = paste(c(var, covar), collapse = ' + ')
formula = substitute(condition ~ (1|subject) + v, list(v = as.name(covar)))
print(formula)

输出

condition ~ (1 | subject) + `a + b + c`

如何删除 a + b + c 周围的额外``?

如果我不与粘贴连接,那么它可以工作,但我需要那些额外的变量......

var = 'a'
formula = substitute(condition ~ (1|subject) + v, list(v = as.name(var)))
print(formula)

输出

condition ~ (1 | subject) + a

var 和 covar 都是 char 类型。

另一种可以迭代地改变公式中的 v 的解决方案,它也可以工作

4

2 回答 2

1

Assume that v is a term by itself (which is the case in the question) and the inputs shown in the Note at the end. Then here are two approaches.

1) update Use reformulate to create the formula ~ . - v + a + b + c and update the input formula with it.

update(fo, reformulate(c(". - v", var, covar)))
## condition ~ (1 | subject) + a + b + c

2) getTerms Another approach is to decompose the formula into terms using getTerms from this post, remove v, append var and covar and reformulate it back into a formula:

reformulate(c(setdiff(sapply(getTerms(fo[[3]]), format), "v"), var, covar), fo[[2]])
## condition ~ (1 | subject) + a + b + c

Note

The inputs are assumed to be:

var <- 'a'
covar <- c('b', 'c')
fo <- condition ~ (1 | subject) + v
于 2021-01-10T14:16:25.393 回答
0

也许我误解了你在做什么,但以下似乎工作:

form  <- 'condition ~ (1|subject) + v'
var   <- 'a'
covar <- c('b', 'c')

然后结合 paste 直接转为公式:

covar <- paste(var, paste(covar, collapse=" + "), sep=" + ")
form  <- formula(paste(form, covar, sep=" + "))

输出:

condition ~ (1 | subject) + v + a + b + c
于 2021-01-10T13:50:39.247 回答