How to build custom functions in R?

I have to write a function for Stirling numbers of the second kind, given by the formula:

enter image description here

To do this, I wrote the following function in R:

stirling <- function(n, k) { sum = 0 for (i in 0:k) { sum = sum + (-1)^(k - i) * choose(k, i) * i^n } sum = sum / factorial(k) return(sum) } 

The next part of the question is "create a graph for n = 20, k = 1,2, ..., 10". I did some research and I think the curve or plot methods might help me. However, I assume that these methods are used when y has the form f(x) (i.e., One argument). But here I have two arguments ( n and k ) in my stirling function, so I'm not sure how to approach this.

In addition, I tried converting the values โ€‹โ€‹of k (0, 1, 2 ..., 10) into a vector and then passing them to stirling , but stirling would not accept vectors as input. I am not sure how to change the code so that stirling accept vectors.

Any suggestions?

+6
source share
1 answer

Vectorize

As stated in the comments, you can vectorize to do this:

Vectorize creates a wrapper for a function that vectorizes the action of its FUN argument. Vectorize(FUN, vectorize.args = arg.names, SIMPLIFY = TRUE, USE.NAMES = TRUE)

 (vstirling <- Vectorize(stirling)) # function (n, k) # { # args <- lapply(as.list(match.call())[-1L], eval, parent.frame()) # names <- if (is.null(names(args))) # character(length(args)) # else names(args) # dovec <- names %in% vectorize.args # do.call("mapply", c(FUN = FUN, args[dovec], MoreArgs = list(args[!dovec]), # SIMPLIFY = SIMPLIFY, USE.NAMES = USE.NAMES)) # } 

therefore vstirling() is a vector version of stirling() .

 vstirling(20, 1:10) # [1] 1.000000e+00 5.242870e+05 5.806064e+08 4.523212e+10 7.492061e+11 4.306079e+12 1.114355e+13 1.517093e+13 # [9] 1.201128e+13 5.917585e+12 

Now all that remains is to create a graph:

 plot(x = 1:10, y = vstirling(20, 1:10), ylab = "S(20, x)", xlab = "x") 
+2
source

All Articles