cosmosa
cosmosa

Reputation: 761

Create string from vector

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

Answers (1)

pogibas
pogibas

Reputation: 28379

You can do this:

x <- c(1, 3)
paste0(x, substitute(x), seq_along(x), collapse = " + ")
# [1] "1x1 + 3x2"

Explanation:

  • Get object name: substitute(x) (this returns "x")
  • Attach object name ("x") to x values and x index seq_alon(x) using paste0() with collapse = " + " argument.

Upvotes: 2

Related Questions