简体   繁体   中英

How do I write a function in R with 2 parameters with a return of a percent?

I am not really experienced with writing functions in R and I'm trying to write a function with 2 parameters - the first is a vector and the second is a number. The function will return the percentage of the elements within the vector that is less than the same (ie the cumulative distribution below the value provided). For example, if the vector had 5 elements (1,2,3,4,5), with 2 being the number passed into the function, the function would return 0.2 (since 20% of the numbers were below 2). This is what I have so far:

testfunction <- function(myVector, x)
{
uniqueCounts(myVector > x)/x
}

You have the correct syntax here

your_function <- function(arg1, arg2){
    do_something
}

Here you also need an expression that will evaluate as you've described. @TimBiegeleisen has provided one for you, sum(a > b) gives the number of occurrences of a value greater than b in the vector a. The proportion sum(a > b)/ length(a) will give you the proportion of values in a that are greater than b, and should range between 0 for vectors a that have no values greater than b and 1 for vectors with all values greater than b , and will give NaN if a is NULL , NA , if a is NA . If you'd like to enforce a and or b having certain properties, you can add error checking.

testfunction <- function(myVector, x){
    sum(myVector > x)/length(myVector)
}
tesfunction(1:10, 2)
# [1] 0.8

In R, the last expression evaluated is returned by the function, if there is no explicit return . If you want to enforce certain properties, you include a call to stop() , eg

testfunction <- function(myVector, x){
  if(length(x) != 1) stop("x must have length == 1")
  sum(myVector > x)/length(myVector)
}
testfunction(1:10, 2:3)
# Error in testfunction(1:10, 2:3) : x must have length == 1

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