R中的函数总和

The*_*kel 1 r

我在R中有一个函数,我希望用不同的值取这个函数的总和.但是,由于我有一个中断条件(由一个if语句做出),我不能明确地这样做:

F<- function(x) if(x<5) 1 else 0
sum(F(seq(1,10,1))
#[1] 1
#Warning message:
#In if (x < 5) 1 else 0 :
#  the condition has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)

所以它试图完成函数的序列而不是序列总和.我希望避免for循环,因为这可能使长代码非常混乱; 特别是为了避免丑陋的嵌套for循环.

我该怎么做?

Sve*_*ein 5

你可以使用Vectorize:

F_v <- Vectorize(F)
sum(F_v(seq(1,10,1)))
# [1] 4
Run Code Online (Sandbox Code Playgroud)