Concatenate two columns of an array by forming a string of characters

5

Suppose I have the following vectors:

n <- c(1:5)
c <- c("A","B","C","D","E")

I build the following array with them:

m <- matrix(c(n,c), ncol = 2)

What is the best way to get a vector like this:

"1 - A", "2 - B", "3 - C", "4 - D", "5 - E"

Do not loop (for / while)?

I can use the

vetor <- paste(m[1,1], m[1,2], sep = " - ")

but only the first element is created:

"1 - A"
    
asked by anonymous 17.01.2017 / 20:28

1 answer

3

Your answer is almost there. Instead of just selecting one row from the array, with the

paste(m[1, 1], m[1, 2], sep = " - ")

Select all at the same time:

paste(m[, 1], m[, 2], sep = " - ")
[1] "1 - A" "2 - B" "3 - C" "4 - D" "5 - E"

In any case, it was not even necessary to create the array m . The R can work directly with the vectors n and c :

paste(n, c, sep = " - ")
[1] "1 - A" "2 - B" "3 - C" "4 - D" "5 - E"
    
17.01.2017 / 20:36