1

同じパッケージ内の関数からパッケージ変数にアクセスするにはどうすればよいですか?

次のコードはx、関数に対してローカルでのみ変更されます。myPackage::xその機能からどのように変更できますか?

例:

x <- list()
populate_list <- function() {
    x["a"] <- 4
}

--

でこれをテストするために使用している完全なコードを次に示しますget。キーは、cacheパッケージが実行されるたびに異なるように選択されます。これはパッケージ コードです。R/get_obj.R

cache <- list()
test_cache <- function(){
    cache <- get("cache")
    cache[[paste(sample.int(10),collapse="-")]] <- 1
    return(cache)
}

Rで次のようにテストします:

> library(devtools)
> load_all("mypackage")
Loading mypackage
> mypackage::test_cache()
$`4-1-6-5-9-3-10-2-7-8`
[1] 1

> mypackage::test_cache()
$`6-9-7-10-5-1-4-2-3-8`
[1] 1

> mypackage::cache
list()

mypackage::cacheと の 2 回目の実行ではmypackage::test_cache()、次のリストが出力として期待されていました。

$`4-1-6-5-9-3-10-2-7-8`
[1] 1

$`6-9-7-10-5-1-4-2-3-8`
[1] 1
4

2 に答える 2

2

オペレーターは<<-親環境で既存の定義を検索するので、以下は私が望むものを私に与えます:

x <- list()
populate_list <- function() {
    x["a"] <<- 4
}

または他の例の場合:

cache <- list()
test_cache <- function(){
    cache[[paste(sample.int(10),collapse="-")]] <<- 1
    return(cache)
}
于 2012-11-19T15:26:38.913 に答える
0

Take a look at the get method. It allows you to pull variables directly from specific environments rather than relying on the lexical scoping of the current method.

The documentation for environments should help make this argument for get more clear though it is difficult to identify the exact syntax without knowing the scenario.

In general it is not a good idea to hide variables by defining them at a local scope if you know you will want to access them more globally.

于 2012-11-19T12:49:04.687 に答える