Tom
Tom

Reputation: 2341

Combining vector elements with paste

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

Upvotes: 0

Views: 182

Answers (2)

user2974951
user2974951

Reputation: 10375

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"

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101149

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"

Upvotes: 2

Related Questions