using apply with assign in R

喜你入骨 提交于 2020-01-02 03:34:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!