Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

r - Applying over a vector of functions

Given a vector (actually a list) of functions:

 fs = c(sin, cos, tan)

and a vector of values:

 xs = c(.1, .3, .5)

Is there a better/neater/faster/stronger way of computing fs[[i]](xs[i]) for each vector element:

 vapply(1:3, FUN.VALUE = 1 ,function(i){fs[[i]](xs[i])})
  [1] 0.09983342 0.95533649 0.54630249

Or am I missing a fapply function somewhere? The functions will always be functions of a single scalar value and returning a single scalar value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nice and simple:

mapply(function(fun, x) fun(x), fs, xs)

But I agree with @flodel. I was also looking for a base function for function(fun, ...) fun(...) and was surprised that there doesn't seem to be one. On the other hand I've never needed it, so far.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...