【问题标题】:Paste named vector R粘贴命名向量 R
【发布时间】:2019-11-18 08:15:49
【问题描述】:

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

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"

【问题讨论】:

    标签: r paste


    【解决方案1】:

    可以使用[&lt;- 来保留属性:

    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" 
    

    【讨论】:

    • 非常感谢。它真的很优雅。有点不完美,这样我必须先影响对象,然后将其用作函数的参数。
    • 你可以做x &lt;- named; x[] &lt;- paste(named, description),但那样就不是很优雅了
    • 是的,我明白了。但是,例如直接作为pickerInput 的参数,我必须在之前添加一个附加的赋值步骤。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多