Reputation: 761
I have a numeric vector. I want to enumerate over the vector and create a string as the result. For example, if I have a vector
x = c(1, 3)
I want the resulting string to be:
y = '1x1 + 3x2'
In Python, I would do this:
l = [1, 3]
equation = ' + '.join(['{}x{}'.format(coef, i + 1) for i, coef in enumerate(l)])
str = 'y = {}'.format(equation)
How can the same thing be done in R?
Upvotes: 1
Views: 238
Reputation: 28379
You can do this:
x <- c(1, 3)
paste0(x, substitute(x), seq_along(x), collapse = " + ")
# [1] "1x1 + 3x2"
Explanation:
substitute(x)
(this returns "x")x
values and x
index seq_alon(x)
using paste0()
with collapse = " + "
argument.Upvotes: 2