簡體   English   中英

在apply() - d函數中使用<<分配變量

[英]assign variables in apply()-d function using <<-

在R,我想打電話申請一個巨大的data.frame,寫值回其他dataframes的特定位置。

但是,使用“<< - ”僅在我從全局環境調用apply函數時才有效。 據我所知,'<< - '在parent.env()中搜索變量。 為什么在bar()中調用的函數的父環境不是bar的環境? 謝謝!

do_write_foo1 <- function(x) {
    cat("parent environment of function called in bar():  ")
    print(parent.env(environment()))
    foo1[x['a']] <<- 100+x['a']
}
do_write_foo2 <- function(x) {
    foo2[x['a']] <<- 100+x['a']
}

bar <- function() {
    cat("bar environment:  ")
    print(environment())
    foo1 <- 1:10
    apply(data.frame(a=1:10),1,do_write_foo1)
    foo1
}

# this does not work:    
bar()
# bar environment:  <environment: 0x3bb6278>
# parent environment of function called in bar():  <environment: R_GlobalEnv>
# Error in foo1[x["a"]] <<- 100 + x["a"] : object 'foo1' not found


# this works:
foo2<-1:10
apply(data.frame(a=1:10),1,do_write_foo2)
foo2
#  [1] 101 102 103 104 105 106 107 108 109 110

由於我在包名稱空間內,我必須使用與Etiennebr不同的解決方案。 我認為它相當優雅:將bar的環境分配給do_write_foo1。

do_write_foo1 <- function(x) {
    cat("parent environment of function called in bar():  ")
    print(parent.env(environment()))
    foo1[x['a']] <<- 100+x['a']
}

bar <- function() {
    cat("bar environment:  ")
    print(environment())
    foo1 <- 1:10
     environment(do_write_foo1) <- environment()
    apply(data.frame(a=1:10),1,do_write_foo1)
    foo1
}

# now it works:    
bar()

似乎R沒有在函數內部搜索(我不明白為什么),所以你需要將值賦給global.env foo。

bar <- function() {
    foo <<-1:10
    apply(data.frame(a=1:10),1,do_write_foo)
    foo
}
bar()
# [1] 101 102 103 104 105 106 107 108 109 110

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM