简体   繁体   中英

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)
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.

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