Combining two strings in R when they are in a vector

Joining two strings in R can readily be done with the paste() command. However, if our strings are part of a vector, paste() no longer works as we might expect.

To illustrate this, assume a list of characters or symbols, and a set of values you want to convert into these characters. The characters “A” to “F” may be more transparent for the example, but it was the bars that led me to this problem: _ ▁ ▂ ▃ ▅ ▇. I use the Unicode values of these bars.

characters = c("A", "B", "C", "D", "E", "F")
characters = c("_", "\u2581", "\u2582", "\u2583", "\u2585", "\u2587")

Let’s start with a couple of random values:

values = runif(5)

In my example, I got:

[1] 0.9568333 0.4533342 0.6775706 0.5726334 0.1029247

Then we want to select one of the characters or symbols based on these values, picking the longer bar for longer values — effectively creating our own histogram (sparkline).

selected = characters[round(values * 5)+1]

This works well, except that we have a series of characters rather than a single string with all the characters included:

"▇" "▂" "▃" "▃" "▁"

My next step was paste() or actually the shorthand paste0() which does not use separation, but it’s not really creating a single string:


[1] "▇" "▂" "▃" "▃" "▁"

enter library(stringr) and the str_c() command:

str_c(selected, sep="", collapse="")

[1] "▇▂▃▃▁"

There we go, a single string…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: