Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a vector of blank spaces of different sizes in R

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.

like image 942
Miquel Avatar asked Sep 19 '25 16:09

Miquel


2 Answers

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] " "          "    "       "      "     "          "
like image 111
Maël Avatar answered Sep 22 '25 18:09

Maël


A possible solution:

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

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

#> [1] " "          "    "       "      "     "          "
like image 41
PaulS Avatar answered Sep 22 '25 16:09

PaulS