Search code examples
ruser-defined-functions

Counting the negative values in vectors with random numbers


I am trying to define a function counting the values that are less than 0 for two vectors x=rnorm(100) and y=rnorm(500).

Define another function to calculate the proportion that values are less than 0 for x and y respectively.

I will like to compare calculated proportions with theoretical proportion 0.5.

myf <- function (x)
{
  a <- rnorm(100)
  b <- x[x < 0]
  return(a)
}

myf (x)

Solution

  • set.seed(92)
    x <- rnorm(100)
    y <- rnorm(500)
    
    countnegatives <- function(a,b){
    
      counta <- sum(a<0); countb <- sum(b<0)
    
    return(
      paste(deparse(substitute(a)), "has", counta, "negative numbers",
            "and",
            deparse(substitute(b)), "has", countb, "negative numbers")
    )}
    
    countnegatives(x,y)
    #> [1] "x has 44 negative numbers and y has 267 negative numbers"
    

    Or you can simply return c(counta, countb) in your function. If you want to get the proportions, you can divide counta/length(a) and the same for b and return that in your function.