4

x, y定義されている場合と定義されていない場合がある一連の変数があるとします。これらの変数は、 という関数に渡されますtest

y <- 10
test <- function(a,b) { ifelse(a > b, "hello", "world") }
test(x,y)

# Error in ifelse(a > b, "hello", "world") : object 'x' not found

x がインスタンス化されていないときに呼び出すとtest(x,y)、R は「オブジェクト 'x' が見つかりません」というエラーをスローします。

存在チェックを追加すると、関数はグローバル環境から呼び出すときに機能します

y <- 10
test <- function(a,b) { 
     print(exists(as.character(substitute(a))))
     if (!exists(as.character(substitute(a)))) {a <- 0}
     ifelse(a > b, "hello", "world")  
}
test(x,y)

# [1] FALSE
# [1] "world"

x <- 11
test(x,y)

[1] TRUE
[1] "hello"

ただし、関数test(x,y)内にラップすると。blah既存の変数が見つかりません。

rm(list=ls())
test <- function(a,b) { 
     print(exists(as.character(substitute(a))))
     if (!exists(as.character(substitute(a)))) {a <- 0}
     ifelse(a > b, "hello", "world")  
}
blah <- function() { x <- 11; y <- 10; test(x,y)}
blah()
[1] FALSE -- expecting TRUE
[1] "world" -- expecting "hello"

失敗の原因は、適切な環境を見ていないためだと思います。これを適切に機能させる方法はありますか?

4

1 に答える 1

5

最初に検索する環境を指定できます。

test <- function(a,b) { 
     print(exists(as.character(substitute(a)), envir=parent.frame()))
     if (!exists(as.character(substitute(a)), envir=parent.frame())) {a <- 0}
     ifelse(a > b, "hello", "world")  
}

こちらです:

y <- 10
test(x,y)

# [1] FALSE
# [1] "world"

x <- 11
test(x,y)

#[1] TRUE
#[1] "hello"

rm(list=ls())

test <- function(a,b) { 
     print(exists(as.character(substitute(a)), envir=parent.frame()))
     if (!exists(as.character(substitute(a)), envir=parent.frame())) {a <- 0}
     ifelse(a > b, "hello", "world")  
}
blah <- function() { x <- 11; y <- 10; test(x,y)}
blah()

#[1] TRUE
#[1] "hello"
于 2015-01-12T21:24:35.287 に答える