[英]Turn a character string into a formula object in base R
I was wondering if there might be a way to turn a character string like "time"
into a formula
object like time ~ 1
in BASE R ?我想知道是否有办法将像"time"
这样的字符串转换为像time ~ 1
in BASE R这样的formula
对象?
Note: By formula
, I mean as used in lm()
.注意:通过formula
,我的意思是在lm()
。
Here is what I tried without success:这是我尝试但没有成功的方法:
a = "time"
formula(bquote(.(noquote(a)))~1)
# Desired output a formula object:
time ~ 1
Use reformulate
使用reformulate
a <- "time"
reformulate("1", a)
## time ~ 1
This also works:这也有效:
formula(paste(a, "~ 1"))
## time ~ 1
Note that lm
can take a character string instead of a formula so we don't actually have to convert the string to a formula (except that a formula has an environment attached to it so in some cases it may make a difference although often it won't).请注意, lm
可以使用字符串而不是公式,因此我们实际上不必将字符串转换为公式(除了公式具有附加的环境,因此在某些情况下它可能会有所作为,尽管通常会获胜) 't)。 Below ch
could have been pasted together from pieces.下面ch
可以从碎片粘贴在一起。 Both of the lm
examples below work but in the first it will show literally Call: lm(formula = ch, data = BOD)
in the output whereas the latter will show the actual formula Call: lm(formula = "demand ~ Time", data = BOD)
in the output.下面的两个lm
示例都可以工作,但在第一个示例中,它会在输出中按字面显示Call: lm(formula = ch, data = BOD)
而后者将显示实际公式Call: lm(formula = "demand ~ Time", data = BOD)
在输出中。
ch <- "demand ~ Time"
lm(ch, BOD)
do.call("lm", list(ch, quote(BOD)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.