简体   繁体   中英

Overriding parts of function definition

With assignInNamespace you can override package functions. That works fine, but I have to override only one line out of 200 function lines. So I have to copy & paste much code. :(

Is there a way to override only parts of a function? Only a variable or another function inside the function?

Yes. You can use body<- . Here's a simple example that changes the last line of setNames

setNames                          ## original function
# function (object = nm, nm) 
# {
#     names(object) <- nm
#     object
# }
# <bytecode: 0x45367a8>
# <environment: namespace:stats>
as.list(body(setNames))           ## look at the function body as a list
# [[1]]
# `{`
# 
# [[2]]
# names(object) <- nm
#
# [[3]]
# object
#
body(setNames)[[3]] <- quote(nm)  ## replace the last line with 'nm'
setNames
# function (object = nm, nm) 
# {
#     names(object) <- nm
#     nm
# }
#<environment: namespace:stats>

Note that you can use grep to find where a certain variable is located in the function body

grep("object", body(setNames))
# [1] 2 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM