Phil
Phil

Reputation: 59

How to define a function that takes an argumente outside the paranthesis like names()

today I came across a question. Normaly every function in R takes arguments within its belonging paranthesis, e.g.

# function definition
f <- function(arg){print(arg)}
# function call
f(arg = 3)

But the built-in function names(), for example, works differently. You would call it like so:

x = 3
names(x) <- "aNumber"

This seems to be special, since the value "aNumber" is not assigned to the function names() as a conventional argument, but rather assigned to the function itself. So my question is how to define such type of functions.

Cheers,

Philipp

Upvotes: 4

Views: 59

Answers (1)

GKi
GKi

Reputation: 39737

You can make a User defined infix operator like:

`%x%` <- function(a, b) {a * b}
2 %x% 3
#[1] 6

a User defined replacement / assignment function like:

`x<-` <- function(x, value) {x * value}
y  <- 2
x(y) <- 3
y
#[1] 6

See also: 3.4.4 Subset assignment or 6.8 Function forms.

Upvotes: 1

Related Questions