2014-03-30 21 views
5

在函數內部有沒有方法可以顯示print或顯示變量的值,而不是在函數調用後將值打印到函數外部?打印或顯示函數內部變量

我幾乎可以肯定有,並認爲代碼被稱爲reveal或類似的東西,但我不記得正確的術語。

my.function <- function(x) { 

    y <- x^2 
# reveal(y) 
# display(y) 

# desired result is to print or display here: 
# [1] 16 

    cat(y) 
    print(y) 
    return(y) 
} 

x <- 4 

my.function(x) 
#16[1] 16 
#[1] 16 

cat(y)print(y)return(y)功能之外的所有打印。感謝您的任何建議。

編輯

我發現了一個類似的問題在這裏:

https://stat.ethz.ch/pipermail/r-help/2002-November/027348.html

從彼得·達爾加德這個問題的反應是取消一個選項叫做buffered outputMisc選項卡下。但是,這似乎不適用於我的情況。也許這些問題是無關的。

+1

我很困惑。你是什​​麼意思,他們在功能之外打印?你所說的是不可能的,因爲'4'甚至沒有傳遞給函數... –

+0

數字16出現在'}'之後。 –

+0

當然它!在定義它之前,沒有辦法將'4'傳遞給函數。 –

回答

8

您可以將print()調用放入該函數中,並且如果執行達到該點,那麼即使稍後發生錯誤,也會在控制檯上生成輸出。

> myf <- function(x){ print(x); y <- x^2; print(y); error() } 
> myf(4) 
[1] 4 
[1] 16 
Error in myf(4) : could not find function "error" 

使用browser()函數作爲調試路由可能更優雅。您可以通過更改選項()設置其工作:

> options(error=recover) 
> myf(4) 
[1] 4 
[1] 16 
Error in myf(4) : could not find function "error" 

Enter a frame number, or 0 to exit 

1: myf(4) 

Selection: 1 
Called from: top level 
Browse[1]> x 
[1] 4 
Browse[1]> y 
[1] 16 
Browse[1]> # hit a <return> to exit the browser 

Enter a frame number, or 0 to exit 

1: myf(4) 

Selection: 0 # returns you to the console 
+0

非常好。瀏覽器功能和調試功能的清晰例子很有價值。如果可以的話,我會加倍努力。 –

4

我喜歡用message功能打印的調試,因爲它似乎無論從那個黑暗的深淵,可能從被髮射進入控制檯。例如:

somefunc <- function(x) { 
     message(paste('ok made it this far with x=',x)) 
     # some stuff to debug 
     message(paste('ok made it this far with x^2=',x^2)) 
     # some more stuff to debug 
     message(paste('ok made it to the end of the function with x^3=',x^3)) 
} 
1

當我問到這個問題,我可能一直在想show功能,讓你看到一個變量的值,而不包括在return聲明的變量。儘管show命令可以在函數外打印值。

my.function <- function(x) { 
    y <- x^2 
    show(y) 
    show(length(y)) 
    z <- y + x 
    return(z) 
} 

x <- 1:10 

my.function(x) 

# [1] 1 4 9 16 25 36 49 64 81 100 
# [1] 10 
# [1] 2 6 12 20 30 42 56 72 90 110