2014-10-03 108 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