Bash SU
Bash SU

Reputation: 13

R function to print negative numbers only

I am trying to create a function in R that a given vector will print only the negative number. I tried the following:

Negative_number <- function (i) {
  return(i <0)
}

print(Negative_number(c(-2,1,3,-5)))

[1] TRUE FALSE FALSE TRUE

Instead of true or false, I want to print the actual negative numbers i.e. -2 & -5 in this case. How can I resolve this?

Upvotes: 1

Views: 927

Answers (2)

gph
gph

Reputation: 1360

You could use the dplyr::filter function

negatives_only <- dplyr::filter(c(-2,1,3,-5), function (x) x < 0)

Any element in the input dataset for which the predicate evaluates to true or NA is returned. All other elements are dropped.

Upvotes: 1

akrun
akrun

Reputation: 887108

In this case, we need to do the subsetting based on the logical vector

Negative_number <- function(i) i[i <0]
Negative_number(c(-2,1,3,-5))
#[1] -2 -5

Upvotes: 3

Related Questions