简体   繁体   中英

Function returning <= with one or two arguments

How to interpret this function?

  g <- function(x,y) y <= x^2

How to call the function? g(2) or g(2,3)? What will it return?

<= is a comparison operator, where you are comparing whether the Left-Hand Side (LHS) is less than or equal to the Rigth-Hand Side. The answer to which will be either TRUE or FALSE .

In your example, the function is returning the result of

2 <= 3^2
[1] TRUE

You will call the function like g(2,3) , as both x and y are required.

g <- function(x,y) y <= x^2

g(2,3)
[1] TRUE

The arguments (x, y) are required because you haven't set any default values for them. To do this you define the values in the arguments of the function

g <- function(x = 2, y = 3) y <= x^2   ## assigned default values 
g()                                    ## using the default values
[1] TRUE

Having the function all on one line is a shorthand of the more explicit

g <- function(x, y){
    return(y <= x^2)
}

g(2,3)
[1] TRUE

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