问题
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?
回答1:
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()))
回答2:
You can also use attach for example:
attach(as.list(setNames(Dat,Vars)))
来源:https://stackoverflow.com/questions/16276667/using-apply-with-assign-in-r