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?

4

2 回答 2

9

这是一个很好的例子,说明何时使用for循环而不是apply.
最好的解决方案是保持原样。

如果您真的想使用*ply循环,请使用mapply

 mapply(assign, Vars, Dat, MoreArgs=list(envir=parent.frame()))
于 2013-04-29T10:53:27.633 回答
2

您还可以使用attach例如:

attach(as.list(setNames(Dat,Vars)))
于 2013-04-29T11:33:01.217 回答