## Function modification on the fly using trace, untrace and substitute
# You want to create a function which is a test version of another function
#lets start by creating a function
# The original function
sum_func <- function(x)
{
y <- 2
return(x+y)
}
# This gives you 5
sum_func(3)
# Use this to view the body of the function. You need this to find out where you need to place the modification
as.list(body(sum_func))
#Save the function into a new function
new_sum_func <- sum_func
#Change the new function body
body(new_sum_func)[[2]] <- substitute(y <- 3)
class(new_sum_func)
as.list(body(new_sum_func)) #You can view the modified function
#The modified function
new_sum_func(3) #This output will be 6
#Suppose instead you want to modify the original function just for testing
# but then you want to revert back to the original
# Use the trace function to insert a piece of code (not overwrite)
trace(sum_func, quote(y <- 4), at = 3)
#The modified test function
as.list(body(sum_func))
sum_func(3) #This gives you 7
#Reset the original code to unchanged version by removing the test changes
untrace(sum_func)
# You get back the original function
sum_func(3) 'this gives you back 5
Hi, Hope this post keeps you in the best of health. I am an oracle user and wanted to know how to fetch database information in R. There is a package out there called ROracle but there are no binaries for it and it thus needs to be built and then installed. Here are the steps to install it on Windows 7 machines. 1. Download the package from http://cran.r-project.org/web/packages/ROracle/index.html. Since I wrote this post the latest that was available was ROracle_1.1-12.tar.gz . 2. Place the package in the directory where R is installed. I placed mine in E:\R\R-3.0.2\bin folder. 3. Install RTools from http://cran.r-project.org/bin/windows/Rtools/. Since my R version is R-3.0.2 the toolkit I needed was RTools31.exe. 4. Install the Rtools software in the R home directory. I placed mine in E:\R\Rtools. Place all the extras in there too. For example I placed my 32 bit extras in E:\R\RExtras32 and the 64 bit in E:\R\RExtras64 folder. These extras are not necessary for ...
Comments
Post a Comment