0

Here's a simple vector:

vec <- c('foo', 'bar', 'baz');

I want to add the suffixes _X and _Y to each element of this vector, so that I get a vector with six elements: c('foo_X', 'foo_Y', 'bar_X', 'bar_Y', 'baz_X', 'baz_Y').

I hoped that I could achieve that with sapply:

sapply(vec, function(elem) {
        c(paste0(elem, '_X'),
          paste0(elem, '_Y'))
     });

However, this returns a matrix rather than a vector:

     foo     bar     baz    
[1,] "foo_X" "bar_X" "baz_X"
[2,] "foo_Y" "bar_Y" "baz_Y"

What can I do to create the vector I want?

René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293

1 Answers1

7

Use outer with paste0

vec <- c('foo', 'bar', 'baz')
suffix <- c("_X", "_Y")
c(outer(vec, suffix, paste0))
#[1] "foo_X" "bar_X" "baz_X" "foo_Y" "bar_Y" "baz_Y"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213