[SOLVED] Please help me in understanding this piece of code

Issue

I have just started learning R from Datacamp and got stuck at the following function:

below_zero <- function(x) {
    return(x[x < 0])
}

Website says that this function does the following:

We already created a function, below_zero(), that takes a vector of
numerical values and returns a vector that only contains the values
that are strictly below zero.

This function will be applied to this list called "temp":

[[1]] [1] 3 7 9 6 -1

[[2]] [1] 6 9 12 13 5

[[3]] [1] 4 8 3 -1 -3

[[4]] [1] 1 4 7 2 -2

[[5]] [1] 5 7 9 4 2

[[6]] [1] -3 5 8 9 4

[[7]] [1] 3 6 9 4 1

But, I’m not really able to understand this part in particular:

(x[x < 0])

If for e.g., x[1] returns the 1st element in the vector then what exactly is [x < 0] doing?

Is x < 0 returning a logical statement or really a number?

Please explain as to what this piece of code is doing.

Thanks

Solution

if you try out x < 0 for the an example vector x <- c(-3,-1,1,2) you will get the result of TRUE TRUE FALSE FALSE since R checks every value of x if it is less than 0. Since the result is a logical vector you can use that as selector for x.
A full example:

x <- c(-3,-1,1,2) # input
y <- x < 0 # logical vector
x[y] # filter

So, you have two options of selection:

  1. by index: as you mentioned with x[1] returns you the first value
  2. by filter x[x < 0] the expression inside the[] tell you if something holds the expression and the outside expression filters accroding to the result of the inner one.

Answered By – Domingo

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.