Concatenate two columns of an array into a string of characters

Asked

Viewed 2,161 times

5

Suppose I have the following vectors:

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

I build the following matrix with them:

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

What is the best way to obtain such a vector:

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

without looping (for/while)?

I can use the command

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

but only the first element is created:

"1 - A"

1 answer

5


Your answer is almost there. Instead of just selecting a matrix line, with the command

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

select all at once:

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

Anyway, it wasn’t even necessary to create the matrix m. The R can work directly with vectors n and c:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.