2014-10-03 46 views
0

我有2个功能,其积分之和为1:集成阶梯函数

> body <- function(x) {dlnorm(x, meanlog=5.141287, sdlog=1.563058)} 
> tail <- function(x) {16.11505*x**-1.752366} 
> integrate(body, 1, 100)$value + integrate(tail, 100, 5002)$value 
[1] 1 

然而,当我从2个功能定义一个阶跃函数,所述阶跃函数的积分不等于1:

> double_pareto <- function(x) {if (x < 100) body(x) else tail(x)} 
> integrate(double_pareto, 1, 5002) 
1.074265 with absolute error < 3.6e-05 
There were 13 warnings (use warnings() to see them) 
> warnings() 
Warning messages: 
1: In if (x < 100) body(x) else tail(x) : 
    the condition has length > 1 and only the first element will be used 

这是为什么?在R中集成step函数的正确方法是什么?

+5

所述的if else应矢量'double_pareto < - 函数(X){ifelse(X <100,mybody(x)的,mytail(x))}' – rawr 2014-10-03 04:19:09

+2

你应该仔细阅读'if'的帮助页面。不幸的是,'ifelse'函数被称为“控制流”的一种方式,因为它实际上是一个函数,但也不幸的是_you_也没有阅读帮助页面。 – 2014-10-03 04:27:39

回答

1

在定义double_pareto功能使用ifelse函数代替if构建体的伎俩:

> double_pareto <- function(x) {ifelse(x < 100, body(x), tail(x))} 
> integrate(double_pareto, 1, 5002)$value 
[1] 1.000004