这可能看起来像一个奇怪的请求,但我希望暂时附加一个对象,以便可以从所述对象中提取单个元素,但不实际使用attach()
或with()
。例如,我很清楚这两种方法可以按名称索引data.frame
个元素"
obj <- data.frame(N=2, sd=1)
myfun <- function(obj){
N2 <- obj$N^2
rnorm(N2, obj$sd)
}
myfun(obj)
myfun2 <- function(obj){
with(obj, {
N2 <- N^2
rnorm(N2, sd)
})
}
myfun2(obj)
然而,我想要的是更通用的东西,表格可以是
# wanted
myfun3 <- function(){
N2 <- N^2
rnorm(N2, sd)
}
with(obj, myfun3()) #this is the idea but clearly doesn't work
因此不需要显式索引obj
的元素,并且可以避免将整个语句包装在with()
函数中。显然myfun3()
找不到obj
的内部,但我希望如此。attach(obj)
myfun3()
detach(obj)
以下工作正常,从功能的角度来看正是我想要的,但远非犹太教徒:
attach()
附加通常被认为是错误的,并且为了我的目的,这个代码必须在R包中工作,所以library(parallel)
cl <- makeCluster()
parfun <- function(index, obj, myfun){
out <- with(obj, myfun())
out
}
parSapply(cl=cl, 1:100, parfun, obj=obj, myfun=myfun3)
甚至不被允许(同样,它嵌套在另一个可以运行的函数中)并行....所以出口到全球环境可能不是一个好的解决方案)。
最终,我希望这一切在安全的并行计算环境中如下工作
import UIKit
class EarthVC: UIViewController {
@IBOutlet var slideShow1: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
slideShow1.animationImages = [
UIImage(named: "Earth1.jpg")!,
UIImage(named: "Earth2.jpg")!,
UIImage(named: "Earth3.jpg")!,
UIImage(named: "Earth4.jpg")!,
UIImage(named: "Earth5.jpg")!,
UIImage(named: "Earth6.jpg")!,
UIImage(named: "Earth7.jpg")!,
UIImage(named: "Earth8.jpg")!,
UIImage(named: "Earth9.jpg")!,
UIImage(named: "Earth10.jpg")!,
UIImage(named: "Earth11.jpg")!,
UIImage(named: "Earth12.jpg")!,
UIImage(named: "Earth13.jpg")!,
UIImage(named: "Earth14.jpg")!,
UIImage(named: "Earth15.jpg")!,
UIImage(named: "Earth16.jpg")!,
UIImage(named: "Earth17.jpg")!,
UIImage(named: "Earth18.jpg")!,
UIImage(named: "Earth19.jpg")!,
UIImage(named: "Earth20.jpg")!,
UIImage(named: "Earth21.jpg")!,
UIImage(named: "Earth22.jpg")!,
UIImage(named: "Earth23.jpg")!,
UIImage(named: "Earth24.jpg")!,
UIImage(named: "Earth25.jpg")!,
UIImage(named: "Earth26.jpg")!,
UIImage(named: "Earth27.jpg")!,
UIImage(named: "Earth28.jpg")!,
UIImage(named: "Earth29.jpg")!,
UIImage(named: "Earth30.jpg")!,
UIImage(named: "Earth31.jpg")!
]
slideShow1.animationDuration = 93
slideShow1.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
任何想法都将不胜感激。
答案 0 :(得分:1)
怎么样:
do.with <- function(context,fun,args=list()){
env <- as.environment(context)
parent.env(env) <- environment(fun)
environment(fun) <- env
do.call(fun,args)
}
context = list(x=1,y=2)
add = function() x + y
do.with(context,add)
context = list(x=2)
parameters = list(y=5)
mult = function(y) x * y
do.with(context,mult,parameters)