Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

Setting Function Defaults R on a Project Specific Basis

Commonly, I use the same function settings. I'm wondering if there is a method, other than having a new object in the path that is essentially a wrapper for the function, to set default arguments. For example:

paste() has it's sep argument set to a space =" ", I'm tired of writing ,sep="" over and over. So is there a way to "temporarily" replace the function with my chosen defaults?

paste(...,sep="") 

Can I accomplish this through packaging? I've sometimes noticed that, some packages force other equally named functions to be masked in the global environment.

Ideally, I'd like something that can be set on a project by project basis in (load.r or some other such workflow startpoint)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd personally be very hesitant to change the default behavior of any commonly used functions --- especially base R functions. For one thing, it will immediately decrease the portability of any scripts or code snippets in which you use the redefined functions. Worse, other R users reading your scripts will likely be either: (a) unaware of your private meanings for well-known language elements or (b) frustrated at having to rewire their own expectations for the functions. For me, it would also feel like an added mental burden to attach different meanings to the same symbol in different settings.

I think a much better solution is to create similarly named functions implementing your preferred defaults. A slightly modified name will effectively flag that this isn't the familiar base function, without burdening you with much or any extra typing. A good example are the paste0() and cat0() functions that are included in the gsubfn package. (Clearly you and I aren't the only two to find ourselves (frequently) annoyed by the paste()'s default sep setting!):

library(gsubfn)

paste0
# function (..., sep = "") 
# paste(..., sep = sep)
# <environment: namespace:gsubfn>

cat0
# function (..., sep = "") 
# cat(..., sep = sep)
# <environment: namespace:gsubfn>

You can then either collect a number of these functions in a text file, sourcing them early in your script, or (better) package them up and load them via a call to library().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...