1) gsub
replaces a pattern with a constant but what you are looking to do is to replace it with the result of applying a function to the matched string. gusbfn
in the gsubfn package does that. Below, the formula in the second argument is just gsubfn's short form for a function whose argument is the left hand side and the body is the right hand side. Alternately the second argument could be expressed in the usual function notation ( function(x) nls[x,]
) but at the expense of a bit of verbosity:
> library(gsubfn)
> gsubfn("a|b|c", x ~ nls[x, ], "a + b*x + c*x^2")
[1] "1 + 2*x + 3*x^2"
Note that "a|b|c"
could be derived from nls
using paste(rownames(nls), collapse = "|")
in order to avoid redundant specification.
2) Although gsubfn
simplifies this significantly, to do it without gsubfn
use substitute
:
> L <- as.list(setNames(nls[[1]], rownames(nls))) # L <- list(a = 1L, b = 2L, c = 3L)
> e <- parse(text = "a + b * x + c * x ^ 2")[[1]] # e is the text as a "call" object
> s <- do.call(substitute, list(e, L)) # perform the substitution
> format(s) # convert to character
[1] "1L + 2L * x + 3L * x^2"
The L
s are due to the fact that nls
as defined in the question contains integers. Convert them to numeric before running the above if you don't like that:
nls[[1]] <- as.numeric(nls[[1]])
3) Another possibility is to loop over the strings to be substituted.
> s <- "a + b*x + c*x^2"
> for(nm in rownames(nls)) s <- gsub(nm, nls[nm, ], s)
> s
[1] "1 + 2*x + 3*x^2"
If we knew there was no more than one occurrence of each to be replaced we could use sub
in place of gsub
here.
UPDATE: Corrected second solution.
UPDATE 2: Added third solution.