0

I have two vectors:

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

I want to combine them, so that the elements of the new vector var_names are 'a' = '1', 'b' = '2', 'c' = '3'.

I tried something like this:

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

But it is not working properly. What am I doing wrong here?

EDIT

I was a bit unclear about this. But what I am trying to achieve is;

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

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

Tom
  • 2,173
  • 1
  • 17
  • 44

2 Answers2

2

Specifically if you want quotes around a and b

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

If you want it all in one string

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

Edit: regarding your edit, did you mean this?

names(new)=old
new
  a   b   c 
"1" "2" "3"
user2974951
  • 9,535
  • 1
  • 17
  • 24
  • Thank you for your answer. I notice that I was a bit unclear about what I wanted to achieve. Please see my EDIT. – Tom May 05 '21 at 09:09
  • Yes, your edit works perfectly. I cannot believe it was so simple.. – Tom May 05 '21 at 09:15
2

Update

According to your update, you can use setNames

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

There are two places you have syntax/logic errors:

  1. You didn't initialize a vector var_name
  2. In for loop, you should use 1:length(new)

Below is a correction and it works

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

and you will see

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

A more efficient way to achieve the same result is using paste or paste0, e.g.,

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

> paste0(old, " = ", new)
[1] "a = 1" "b = 2" "c = 3"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81