r - 粘贴命名向量 R

标签 r paste

我想粘贴一个命名向量和一个字符串。有没有办法保留名字?

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/

相关文章:

linux - 在 RHEL 6 上安装 R

r - 按观察次数过滤ggplot2密度图

r - 不能使用粘贴来获取函数内的真实对象

r - ergm/statnet 包可以处理丢失的属性数据吗?

返回一个函数的代码

vim - 在 Vim 中换行?

vim - 用粘贴缓冲区的内容替换单词?

r - paste0-在 plyr :rename (now with update) 中构建一个参数

r - 如何在水平条形图中的条形右侧添加计数标签?

excel - 如何在不包含 ActiveXButton 的情况下复制/粘贴工作表数据