Clemsang
Clemsang

Reputation: 5481

Paste named vector R

I would like to paste a named vector and a string. Is there a way to keep names?

named <- c(first = "text 1", second = "text 2")
description <- c("description 1", "description 2")

Expected result is:

setNames(paste(named, description), names(named))

>                first                 second 
"text 1 description 1" "text 2 description 2" 

But it is redondant as the names are already in the vector. Is there an other way to preserve names without duplicating access to variables?

paste(named, description)

> "text 1 description 1" "text 2 description 2"

Upvotes: 6

Views: 1605

Answers (1)

s_baldur
s_baldur

Reputation: 33488

You can use [<- to preserve attributes:

named[] <- paste(named, description)

                 first                 second 
"text 1 description 1" "text 2 description 2" 

This solution has the disadvantage of messing up your existing named vector. You could avoid it with two steps:

x <- named 
x[] <- paste(named, description)

Or make a function:

foo <- function(x, y) setNames(paste(x, y), names(x))
foo(named, description)

                 first                 second 
"text 1 description 1" "text 2 description 2" 

Upvotes: 9

Related Questions