0

I am using RStudio 2022.12.0 and I would like to create variable names through a vector of strings.

My vector is:

names <- c("John", "Mike", "Tom", "Ben", "Nathalia", "Stephanie")

I was trying to use a look to create a varable name from every name in the vektor.

for (x in names)
{x <- print(paste("The name is", x))}

This produces the following error msg:

Error in print(paste(x)) <- print(paste("The name is", x)) :could not find function "print<-"
    If i change the code to
    for (x in names){
    x <- print(paste("The name is", x))
    }

it prints:

\[1\] "The name is John"

\[1\] "The name is Mike"

\[1\] "The name is Tom"

\[1\] "The name is Ben"

\[1\] "The name is Nathalia"

\[1\] "The name is Stephanie"

But I do not get 6 variable named John, Mike, ..., Stepganie.

enter image description here

I would be please if anybody could help me.

Thank you

    for (x in names){
      x <- print(paste("The name is", x))
    }

I expected to get something like

John <- c("The name is John")
Phil
  • 7,287
  • 3
  • 36
  • 66
JR1
  • 1
  • 2
  • 1
    `print` doesn't have return value. So you can't assign. You may need to store the output in a vector or list i.e. `x1 <- character(length(names)); for(i in seq_along(names)) x1[i] <- paste("The name is", names[i])` – akrun Jan 05 '23 at 23:04
  • Does this answer your question? [Convert string to a variable name](https://stackoverflow.com/questions/6034655/convert-string-to-a-variable-name) – divibisan Jan 05 '23 at 23:11

1 Answers1

1

As @akrun states, you aren’t indexing your loop properly. His correct recommendation will give you a variable x of length 6 each with “The name is whatever name” However if you truly want something like:

John <- c("The name is John")

You can use assign to output the name as an object in the global environment. You can do both in the same loop:

nnames <- c("John", "Mike", "Tom", "Ben", "Nathalia", "Stephanie")

x <- c()
for (i in nnames){
    x[i]<- paste("The name is", i)
    assign(i, x[i])
}
#test
x
John
Tom

Note I changed names to nnames since it is not good practice to name things after inherent functions in R (names is already a base R function)

jpsmith
  • 11,023
  • 5
  • 15
  • 36