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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With