1

I have two vectors:

years<-c(1995:1999)
values<-c(1:5)

I want to create five objects, named "Obj1995", "Obj1996" etc., and assign them the values in values in that order, so that Obj1995==1, Obj1996==2 etc.

I tried using assign():

assign(paste0("Obj",years),values)

but that's not vectorized, so it only created one object, containing all of values:

In assign(paste0("Obj",years),values) :
  only the first element is used as variable name

Is there a way of achieving my goal without a for-loop?

3
  • 1
    Fyi, the usual advice is: don't do that. Both don't create a bunch of objects that naturally fit together in one object; and don't embed data (in this case years) in strings. That is, yr_DF = data.frame(yr = years, v = values) or similar... Commented Oct 18, 2018 at 18:23
  • Thanks, I'm aware of this advice, and have taken it into consideration. The actual use case isn't as simple as the example, and while I could put everything into a list, having multiple-dimension arrays as list objects just becomes too cumbersome to reference for my needs. Commented Oct 18, 2018 at 18:29
  • 1
    library("fortunes"); fortune(236) Commented Oct 18, 2018 at 19:50

1 Answer 1

4

We can use list2env on a named list

list2env(as.list(setNames(values, paste0("Obj", years))), envir = .GlobalEnv)

Obj1995
#[1] 1
Obj1996
#[1] 2

The assign can be used with a for loop

rm(list = ls(pattern = "^Obj\\d{4}$")) # remove any objects 
for(i in seq_along(values)) assign(paste0("Obj", yearsi]), value = values[i])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Yes, I figured out the for-loop option myself, but wanted to figure out a vectorized alternative. Your answer flipped years and values, but I got the gist of it, and got it to work. I actually saw list2env in another answer, but it didn't have the satNames part, and I couldn't figure that bit out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.