user3579016
user3579016

Reputation: 1

R RStudio Resetting debug / function environment

I am trying to stop R from displaying function code and environment information when I call a function. This function is part of an assignment for Coursera R Programming that was provided by the instructor. Here is the behavior:

R script:

makeVector <- function(x = numeric()) {
        m <- NULL
        set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setmean <- function(mean) m <<- mean
        getmean <- function() m
        list(set = set, get = get,
             setmean = setmean,
             getmean = getmean)
}

I run the following in the console:

> x <- 1:10
> makeVector(x)

And get:

$set
function (y) 
{
    x <<- y
    m <<- NULL
}
<environment: 0x000000000967dd58>

$get
function () 
x
<environment: 0x000000000967dd58>

$setmean
function (mean) 
m <<- mean
<environment: 0x000000000967dd58>

$getmean
function () 
m
<environment: 0x000000000967dd58>

It appears RStudio is returning function code and environment information rather than executing the function. Previously I ran debug(ls) and undebug(ls) as part of a quiz - it is my hunch that the debug() command has something to do with the behavior.

To fix the problem, I have already tried:

Does anyone know why RStudio is displaying function code and environment rather than executing the function?

I really appreciate the help! Thanks!

Upvotes: 0

Views: 3993

Answers (1)

tonytonov
tonytonov

Reputation: 25608

First of all, this has nothing to do with Rstudio: Rstudio is just an IDE, it would be very strange if it somehow managed to mess with your code, wouldn't it? The behaviour you see is completely fine and does exactly what it should. If you are familiar with OOP, what you get is an "object" with several methods. Here's a small demo that shows the intended usage:

x <- 1:10
xx <- makeVector(x)
xx$get()
# [1]  1  2  3  4  5  6  7  8  9 10
xx$getmean()
#NULL
xx$setmean(mean(x))
xx$getmean()
#[1] 5.5
xx$setmean("Hi, I am a mean")
xx$getmean()
#[1] "Hi, I am a mean"

Upvotes: 5

Related Questions