Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a function from an R script?

Tags:

r

I made a function mean() taking no arguments. Actually I wanted to calculate mean of some numbers:

mean <- function() {
    ozonev <- data[1]
    mv <- is.na(ozonev)
    mean(ozonev)
}

As there exists a pre-defined function mean() in R, this code is going into recursion. Also, I tried to rename the main function but the previous mean still exists. can any body help me with how to remove that mean function made by me so as to recover the actual functionality of mean().

> source("solution.R")

> ls()

 [1] "colname" "data"    "firtr"   "fsr"     "last"    "mean"    "meano"  
 [8] "missv"   "rowno"   "x"       "y" 

solution.R is the script and mean is the function. meano is the renamed function.

like image 670
Janusz01 Avatar asked Feb 14 '15 09:02

Janusz01


3 Answers

You should use rm to remove your mean function.

rm(mean)
# or, if you have an environment for this
rm(mean, envir = "<your_env>")

But you can't remove the mean from the base package. It's locked for modification.

like image 137
m0nhawk Avatar answered Oct 18 '22 03:10

m0nhawk


Try this.

mean <- NULL

(I don’t know exactly why this works. But this works.)

like image 23
plhn Avatar answered Oct 18 '22 02:10

plhn


There’s a very easy way of avoiding the recursion: call base::mean explicitly:

mean <- function() {
    ozonev <- data[1]
    mv <- is.na(ozonev)
    base::mean(ozonev)
}

Alternatively, you can do something like this:

old_mean <- mean
mean <- function() {
    ozonev <- data[1]
    mv <- is.na(ozonev)
    old_mean(ozonev)
}

This has the advantage that it will call any pre-existing mean function that may previously have overridden base::mean. However, a cleaner approach is usually to make a function into an S3 generic, and creating a generic for a certain class.

You can edit the function inside the R script, or inside your interactive R session by typing the command

man <- edit(main)

(Note that you need to reassign the result of edit, as I’ve done here!)

like image 43
Konrad Rudolph Avatar answered Oct 18 '22 03:10

Konrad Rudolph