如何在R中绘制用户定义的函数?

leb*_*ski 8 math plot r set ggplot2

我应该为第二类斯特林数写一个函数,由下式给出:

在此输入图像描述

为此,我在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)
}
Run Code Online (Sandbox Code Playgroud)

问题的下一部分是"为n = 20创建一个图,k = 1,2,...,10".我做了一些研究,我认为这些方法curve或者plot可能对我有帮助.但是,我猜这些方法是y在形式f(x)(即单个参数)时使用.但是在这里,我的函数中有两个参数(nk),stirling所以我不知道如何处理它.

此外,我尝试将k(0,1,2 ...,10)的值转换为矢量,然后将它们传递给stirling,但stirling不接受矢量作为输入.我不知道如何修改代码来生成stirling接受向量.

有什么建议?

Ken*_*HBS 5

Vectorize

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

Vectorize creates a function wrapper that vectorizes the action of its argument FUN. 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))
# }
Run Code Online (Sandbox Code Playgroud)

so vstirling() is the vectorized 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
Run Code Online (Sandbox Code Playgroud)

Now all that is left is creating a plot:

plot(x = 1:10, y = vstirling(20, 1:10), ylab = "S(20, x)", xlab = "x")
Run Code Online (Sandbox Code Playgroud)