Reputation: 1698
I am having problems with replacing parts of a single string with a set of vector replacements, to result in a vector.
I have a string tex
which is intended to tell a diagram what text to put as the node (and other) labels.
So if tex
is "!label has frequency of !frequency"
and T
has columns label
with values c("chickens","ducks",...)
and frequency
with values c("chickens","ducks",...)
amongst others,
the function returns a vector like c("Chickens has frequency of 35","Ducks has frequency of 12",...)
More formally, the problem is:
Given a tibble T
and a string tex
,
return a vector with length nrow(T)
, of which each element = tex
but in which each occurrence within tex
of the pattern !pattern
is replaced by the vectorised contents of T$pattern
I looked at Replace string in R with patterns and replacements both vectors and String replacement with multiple string but they don't fit my usecase. stringr::str_replace() doesn't do it either.
Upvotes: 0
Views: 159
Reputation: 27732
possible baseR-solution using sprintf()
animals = c("chickens","ducks")
frequency = c(35,12)
sprintf( "%s has frequency of %s", animals, frequency)
[1] "chickens has frequency of 35" "ducks has frequency of 12"
also,
tex = "%s has frequency of %s"
sprintf( tex, animals, frequency )
will gave the same results.
Upvotes: 1