我想粘贴一个命名向量和一个字符串。有没有办法保留名字?
named <- c(first = "text 1", second = "text 2")
description <- c("description 1", "description 2")
预期结果是:
setNames(paste(named, description), names(named))
> first second
"text 1 description 1" "text 2 description 2"
但它是多余的,因为名称已经在向量中。有没有其他方法可以在不重复访问变量的情况下保留名称?
paste(named, description)
> "text 1 description 1" "text 2 description 2"
最佳答案
您可以使用 [<-
保留属性:
named[] <- paste(named, description)
first second
"text 1 description 1" "text 2 description 2"
此解决方案的缺点是会弄乱您现有的
named
向量。你可以通过两个步骤来避免它:x <- named
x[] <- paste(named, description)
或者做一个函数:
foo <- function(x, y) setNames(paste(x, y), names(x))
foo(named, description)
first second
"text 1 description 1" "text 2 description 2"
关于r - 粘贴命名向量 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58910375/