4

I have a vector of "sizes" or "widths", like this one:

x <- c(1, 4, 6, 10)

and I would like to create another vector based on x, a vector like this one:

y <- c(" ", "    ", "      ", "          ")

Basically there are two imputs for creating y: the blank space " " and the vector x.

So as you can see, the vector x defines the length of the blank spaces in y. I know I can do this creating a function from scratch, but I'm guessing if there's some kind of function or combination with rep, paste0 or other built in functions in R.

Any idea? thanks.

Maël
  • 45,206
  • 3
  • 29
  • 67
Miquel
  • 442
  • 3
  • 14
  • Related: [Repeat and concatenate a string N times](https://stackoverflow.com/questions/22359127/repeat-and-concatenate-a-string-n-times) – Henrik Aug 09 '22 at 13:28

4 Answers4

5

Use strrep:

strrep(" ", c(1, 4, 6, 10))
#> [1] " "          "    "       "      "     "          "

In stringr, you can also use str_dup:

stringr::str_dup(" ", c(1, 4, 6, 10))
#> [1] " "          "    "       "      "     "          "
Maël
  • 45,206
  • 3
  • 29
  • 67
2

A possible solution:

x <- c(1, 4, 6, 10)

sapply(x, \(y) paste0(rep(" ", y), collapse = ""))

#> [1] " "          "    "       "      "     "          "
PaulS
  • 21,159
  • 2
  • 9
  • 26
1

Here is a solution.

x <- c(1, 4, 6, 10)
y <- sapply(x, \(n) formatC(" ", width = n))
y
#> [1] " "          "    "       "      "     "          "

Created on 2022-08-09 by the reprex package (v2.0.1)

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
1
library(stringr)

x <- c(1, 4, 6, 10)

y <- str_pad(" ", width = x)

y
#> [1] " "          "    "       "      "     "          "

Created on 2022-08-09 by the reprex package (v2.0.1)

Carl
  • 4,232
  • 2
  • 12
  • 24