结合矢量元素与粘贴

Combining vector elements with paste

我有两个向量:

old <- c("a", "b", "c")
new <- c("1", "2", "3")

我想把它们组合起来,这样新向量var_names的元素是'a' = '1''b' = '2''c' = '3'

我试过这样的事情:

for (i in length(new)){
    var_names[i] <- paste(old[i], "=", new[i])
}

但是它不能正常工作。我在这里做错了什么?

编辑

这个我有点不清楚。但我想要实现的是;

var_names<- c('a' = '1',
              'b' = '2',
              'c' = '3')

原因:https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.html#coef-map

特别是如果你想在 a 和 b 周围加上引号

paste0("'",old,"'"," = ","'",new,"'")
[1] "'a' = '1'" "'b' = '2'" "'c' = '3'"

如果你想把它全部放在一个字符串中

paste0("'",old,"'"," = ","'",new,"'",collapse=", ")
[1] "'a' = '1', 'b' = '2', 'c' = '3'"

编辑:关于您的编辑,您是这个意思吗?

names(new)=old
new
  a   b   c 
"1" "2" "3"

更新

根据您的更新,您可以使用setNames

> setNames(new, old)
  a   b   c
"1" "2" "3"

您有两个地方 syntax/logic 错误:

  1. 你没有初始化向量var_name
  2. for循环中,你应该使用1:length(new)

下面是更正并且有效

var_names <- c()
for (i in 1:length(new)) {
  var_names[i] <- paste(old[i], "=", new[i])
}

你会看到

> var_names
[1] "a = 1" "b = 2" "c = 3"

获得相同结果的更有效方法是使用 pastepaste0,例如

> paste(old, new, sep = " = ")
[1] "a = 1" "b = 2" "c = 3"

> paste0(old, " = ", new)
[1] "a = 1" "b = 2" "c = 3"