简体   繁体   中英

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 ?

Note: By formula , I mean as used in lm() .

Here is what I tried without success:

a = "time"

formula(bquote(.(noquote(a)))~1)

# Desired output a formula object:

time ~ 1

Use reformulate

a <- "time"
reformulate("1", a)
## time ~ 1

This also works:

formula(paste(a, "~ 1"))
## time ~ 1

lm

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). Below ch could have been pasted together from pieces. 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.

ch <- "demand ~ Time"

lm(ch, BOD)
do.call("lm", list(ch, quote(BOD))) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM