Moe Sam
Moe Sam

Reputation: 63

concatenate strings in a character vector based on element names

I have a named character vector, a, that I would like to concatenate some of its elements based on their name

a <- c('item 1' = 'first_i1', 'item 1' = 'second_i2', 'item 2' = 'only_i2')
a
     item 1      item 1      item 2 
 "first_i1" "second_i2"   "only_i2" 

expected result using blank space as the separator

a_out <- c('item 1' = 'first_i1 second_i2', 'item 2' = 'only_i2')
a_out
              item 1               item 2 
"first_i1 second_i2"            "only_i2"

Upvotes: 1

Views: 179

Answers (1)

akrun
akrun

Reputation: 886938

We can concatenate with paste by using grouping variables as the names of the vector 'a'

tapply(a, names(a), FUN = paste, collapse = ' ')
#            item 1               item 2 
#"first_i1 second_i2"            "only_i2" 

Upvotes: 1

Related Questions