Cle*_*ang 2 r paste named-vector
我想粘贴一个命名向量和一个字符串。有没有办法保留名字?
named <- c(first = "text 1", second = "text 2")
description <- c("description 1", "description 2")
Run Code Online (Sandbox Code Playgroud)
预期结果是:
setNames(paste(named, description), names(named))
> first second
"text 1 description 1" "text 2 description 2"
Run Code Online (Sandbox Code Playgroud)
但这是重复的,因为名称已经在矢量中。还有其他方法可以保留名称而不重复访问变量吗?
paste(named, description)
> "text 1 description 1" "text 2 description 2"
Run Code Online (Sandbox Code Playgroud)
您可以使用[<-保留的属性:
named[] <- paste(named, description)
first second
"text 1 description 1" "text 2 description 2"
Run Code Online (Sandbox Code Playgroud)
该解决方案具有使现有named向量混乱的缺点。您可以通过两个步骤避免它:
x <- named
x[] <- paste(named, description)
Run Code Online (Sandbox Code Playgroud)
或做一个功能:
foo <- function(x, y) setNames(paste(x, y), names(x))
foo(named, description)
first second
"text 1 description 1" "text 2 description 2"
Run Code Online (Sandbox Code Playgroud)