noname noname - 1 year ago 112
R Question

R: function and argument

I have to find solution to this question:

Create the function a=b+200 so that the argument b has the value 10 if user does not give it any other value.

I have tired if and else statement, but it didnĀ“t work.. I would be grateful, if someone could help me.

Answer Source

The default value of a variable to be used in a function, in this case b, can be specified in the list of arguments that are passed to the function by using an equal sign. To set the default value to 10, we could use the following code:

a <- function(b=10){b + 200}

This defines a function a() that takes one argument b and returns the value b + 200. If the value of b is not provided in the function call, the default value 10 is used for b, thereby returning 210.

#> a(2)
#[1] 202
#> a()
#[1] 210
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download