Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view value of a variable inside a function? [duplicate]

Tags:

r

Possible Duplicate:
General suggestions for debugging R?

When debugging, I would often like to know the value of a variable used in a function that has completed executing. How can that be achieved?

Example:

I have function:

MyFunction <- function() {
    x <- rnorm(10) # assign 10 random normal numbers to x
    return(mean(x))
}

I would like to know the values stored in x which are not available to me after the function is done executing and the function's environment is cleaned up.

like image 307
Dmitrii I. Avatar asked Nov 18 '25 06:11

Dmitrii I.


2 Answers

You mentioned debugging, so I assume the values are not needed later in the script, you just want to check what is happening. In that case, what I always do is use browser:

MyFunction <- function() {
    browser()
    x <- rnorm(10) # assign 10 random normal numbers to x
    return(mean(x))
}

This drops you into an interactive console inside the scope of the function, allowing you to inspect what is happening inside.

For general information about debugging in R I suggest this SO post.

like image 174
Paul Hiemstra Avatar answered Nov 20 '25 19:11

Paul Hiemstra


MyFunction <- function() {
    x <- rnorm(10) # assign 10 random normal numbers to x
    return(list(x,mean(x)))
}

This will return a list where the first element is x and the second is its mean

like image 33
chandler Avatar answered Nov 20 '25 21:11

chandler