Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste named vector R

Tags:

r

paste

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"
like image 427
Clemsang Avatar asked Jan 01 '23 12:01

Clemsang


1 Answers

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" 
like image 137
sindri_baldur Avatar answered Jan 09 '23 03:01

sindri_baldur