(R) How can I forcefully replace a vector element in a formula?

I am trying to use a formula expressed in terms of a vector element. However, when you build a formula, the item is not replaced; instead, it remains as a component --- I would prefer the actual value to be replaced immediately. (This will break something else in the code.)

c <- c(5:8)  #made a vector on purpose, even though only use c[1]   
form <- as.formula(y ~ exp(-(x-c[1])^2/2))

      

at this point form

contains y ~ exp(-(x - c[1])^2/(2))

, but I would like it to contain y ~ exp(-(x - 5)^2/(2))

.

+3


source to share


1 answer


bquote

makes it easy to connect vlaues to formulas. for example

form <- bquote(y ~ exp(-(x- .( c[1]) )^2/2))
form
# y ~ exp(-(x - 5L)^2/2)

      



Note that add "L" to indicate an integer literal value (as opposed to a generic numeric value). This is because it 5:8

creates an integer vector.

+6


source







All Articles