简体   繁体   中英

Writing a function in R that uses vector operations so it can be applied to a vector

I am teaching a class that has a group of complete R beginners. We came across the task of plotting a function that takes a vector and a scalar and does some complicated calculation with it. I simplified it to this, which is the part that is giving me hard time:

myfun <- function(xs, mu){
   sum((xs - mu)^2)
}

I like this way of defining the function, because it is very simple and directly corresponds to the mathematical sigma notation that is actually used in the definition of the function we are plotting. The function works fine when I apply to a vector and a scalar: myfun(c(1, 2, 3), 5)

The problem is, when I try to plot it (as a function of mu), it will get applied to a vector. Then the subtraction in the sum gets completely different meaning, and the whole thing fails, with the plot ending up completely incorrect.

I can fix it by defining the function like this:

myfun <- function(xs, mu){
   sapply(mu, function(x) {sum((xs - x)^2)})
}

or, using purrr , by somewhat shorter

myfun <- function(xs, mu){
   map_dbl(mu, ~sum((xs - .x)^2))
}

Both of those add an extra layer of complexity on top of the simple summation that appears in the definition of the function.

My question is: what is the simplest, easiest to explain way to define a function like this so it will plot nicely using ggplot2 (actually, ggformula)?

myfun_v <- Vectorize(myfun)

这将为您提供该函数的矢量化版本。

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