7

Consider the following example:

Vars <- c("car","bike","lorry")
Dat <- c(10,20,22)

for (i in 1:length(Vars)){
  assign(Vars[i],Dat[i])
}

Here, I would like to generate three variables in the workspace named according to the entries in Vars and the values in Dat. At the moment I am using a loop, but I have been trying to remove the loop by using apply, how would be the best way of doing this?

ymn
  • 2,175
  • 2
  • 21
  • 39
KatyB
  • 3,920
  • 7
  • 42
  • 72
  • 3
    Why do you want to remove the loop if it works for you? – A5C1D2H2I1M1N2O1R2T1 Apr 29 '13 at 10:47
  • This is included as part of a much larger script which is driven by a for loop, so I was trying to remove this second loop thinking it would be better programming practice. – KatyB Apr 29 '13 at 10:55
  • From the answer below I see that a loop may be better in this instance, it seems more readable than using mapply, thanks for your comments. – KatyB Apr 29 '13 at 11:00
  • 1
    Kate, there are often several ways to get things done with R, and each has its place at the right time.... :) – A5C1D2H2I1M1N2O1R2T1 Apr 29 '13 at 11:09

2 Answers2

9

This is a great example of when to use a for loop instead of an apply.
The best solution is to leave it as it is.

if you really want to use an *ply loop, use mapply

 mapply(assign, Vars, Dat, MoreArgs=list(envir=parent.frame()))
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
  • Just out of curiosity: why would you prefer a loop over mapply? Only for better readability? – dufei Aug 05 '20 at 11:50
2

You can also use attach for example:

attach(as.list(setNames(Dat,Vars)))
user1609452
  • 4,406
  • 1
  • 15
  • 20