Using apply with an assignment in R

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 . I'm currently using a loop, but I'm trying to remove a loop with apply, what would be the best way to do this?

+6
source share
2 answers

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

if you really want to use the *ply use mapply

  mapply(assign, Vars, Dat, MoreArgs=list(envir=parent.frame())) 
+7
source

You can also use attach , for example:

 attach(as.list(setNames(Dat,Vars))) 
+2
source

All Articles