【问题标题】:concatenating strings to make variable name连接字符串以生成变量名
【发布时间】:2013-05-13 21:14:51
【问题描述】:

我想更改我的 R 函数的输出名称以反映输入的不同字符串。这是我尝试过的:

kd = c("a","b","d","e","b")

test = function(kd){

  return(list(assign(paste(kd,"burst",sep="_"),1:6)))

}

这只是一个简单的测试功能。我收到警告(这对我来说同样是一个错误):

Warning message:
In assign(paste(kd, "burst", sep = "_"), 1:6) :
  only the first element is used as variable name

理想情况下,我会得到 a_burst = 1、b_burst = 2 等输出,但还没有接近。

我想通过向量的内容拆分数据框,并能够根据该向量的名称命名所有内容,类似于

How to split a data frame by rows, and then process the blocks?

但不完全是。命名是必须的。

【问题讨论】:

    标签: r split string-concatenation


    【解决方案1】:

    可能是这样的吧?

    kd = c("a","b","d","e","b")
    
    test <- function(x){
        l <- as.list(1:5)
        names(l) <- paste(x,"burst",sep = "_")
        l
    }
    
    test(kd)
    

    【讨论】:

    • 正是我想要的。非常感谢!
    【解决方案2】:

    您可以通过 setNames 使用向量而不是列表:

    t1_6 <- setNames( 1:6, kd)
    t1_6
       a    b    d    e    b <NA> 
       1    2    3    4    5    6 
    
    > t1_6["a"]
    a 
    1 
    

    再次查看这个问题,我想知道您是否想要为字符向量分配顺序名称:

    > a1_5 <- setNames(kd, paste0("alpha", 1:5))
    > a1_5
    alpha1 alpha2 alpha3 alpha4 alpha5 
       "a"    "b"    "d"    "e"    "b" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      相关资源
      最近更新 更多