I'm wondering how I can define a way such that if a user of a function provided an input value in "percentages" then before using these input values, the function converts these percentages to a corresponding ordinary numeric values to be used in the function?
Note: By percentage as input value, I literally mean a user could put 12.5% or 1.5% etc. and so these values be converted to .125 and .015.
A simple annotated R example is below:
Accept.percent = function(x) { # "x" can be as small as ".013" & as large as ".85"
# but user can provide "1.3%" to "85%"
cdf <- pbeta(x, 4, 2) # and we can convert the input values
# provided as percentages to a corresponding
return(cdf) # ordinary numeric values before use.
}
## Example of use:
Accept.percent(.013)
Sure, you can cut off the % sign, convert to a numeric variable and divide by 100
x2 <- as.numeric(substr(x, 1, nchar(x)-1)) / 100
Then use x2
in your call to pbeta()
Do you need to allow for the percentage sign too? If not, you can do it by adding a condition and a coorespondong argument:
my_fun <- function(x, percentage = FALSE){
if (percentage) x <- x/100
(rest of function goes here)
}
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.