1

What I would like is to have a variable like

testNewYork <- "EEUU"

but I would like to keep the "test" part static, and then have the "NewYork" part as a variable. For instance something like

test+(city) <- "EEUU"

So, then I can have a loop, where city could be NewYork, but then it could be other city

hrbrmstr
  • 71,487
  • 11
  • 119
  • 180
  • 4
    I don't know `r`, but dynamically naming variables like that is almost always poor practice. Use a dictionary/map instead. – Carcigenicate Nov 11 '18 at 16:22
  • 2
    +100 @Carcigenicate. "Magically" appearing variables in the global environment is a pretty non-intuitive side-effect. Create a new environment or list to store named entities. – hrbrmstr Nov 11 '18 at 16:26
  • 1
    Make a list called `test`, then create a list element name `"NewYork"` (or any other city) to contain something. `test = list(); test[["NewYork"]] = "EEUU"`. See [How do I make a list of data frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for discussion and examples. – Gregor Thomas Nov 11 '18 at 16:29
  • OMGosh @Gregor I had just used that same exact idiom for an answer. – hrbrmstr Nov 11 '18 at 16:30
  • @hrbrmstr it's almost as if it's the right way to do it! (Already upvoted your answer.) – Gregor Thomas Nov 11 '18 at 16:30

2 Answers2

3

Don't do this. Use a list or an environment:

test <- list()
test$NewYork <-  "ABCD"
test$SanFrancisco <-  "EFGH"
test$Houston <- "IJKL"

str(test)
## List of 3
##  $ NewYork     : chr "ABCD"
##  $ SanFrancisco: chr "EFGH"
##  $ Houston     : chr "IJKL"

test$NewYork
## [1] "ABCD"

test[["NewYork"]]
## [1] "ABCD"

test$Portland <- "MNOP"

str(test)
## List of 4
##  $ NewYork     : chr "ABCD"
##  $ SanFrancisco: chr "EFGH"
##  $ Houston     : chr "IJKL"
##  $ Portland    : chr "MNOP"
hrbrmstr
  • 71,487
  • 11
  • 119
  • 180
1

You need assign. You can put this in a loop and change city in every loop -

city <- "NewYork"
assign(paste0("test", city), "EEUU")
Shree
  • 9,963
  • 1
  • 11
  • 31
  • This is formally right but conceptualy wrong, see the comments and answers above. (@hrbrmstr Not my downvote.) – Rui Barradas Nov 11 '18 at 16:30
  • @hrbrmstr yeah, surprised by the downvote. Only trying to answer OP's question. I usually refrain from advising posters unless I have detailed info on what they are trying to achieve. This post hardly has any details. – Shree Nov 11 '18 at 16:41