问题描述
假设我有
PIL
我的概率密度是使用R内置函数cImage
通过R中的核密度估计器(高斯)估计的。问题是如何对估计密度的平方进行积分。哪个值无关紧要,让我们假设在set.seed(2020) # make the results reproducible
a <- rnorm(100,1)
和density
之间。我尝试了以下方法:
-Inf
解决方法
这里有两个问题。首先,您在select t1.id,t1.name
max(case when t2.rn = 1 then t2.name end) person_1,max(case when t2.rn = 2 then t2.name end) person_2,max(case when t2.rn = 3 then t2.name end) person_3,...
from t1
inner join (
select t2.*,row_number() over(partition by id order by name) rn
from t2
) t2 on t2.id = t1.id
group by t1.id,t1.name
中将x
和y
弄错了方向。其次,不能将函数名称相乘。您需要指定一个新函数,以提供原始函数的平方:
approxfun
我们还可以绘制原始密度函数和平方密度函数:
set.seed(2020)
a <- rnorm(100,1)
f <- approxfun(density(a)$x,density(a)$y)
f2 <- function(v) ifelse(is.na(f(v)),f(v)^2)
integrate (f2,-Inf,Inf)
#> 0.2591153 with absolute error < 0.00011
,
这是使用包caTools
,函数trapz
的一种方法。它使用trapezoidal rule计算给定向量x
的积分及其对应的图像y
。
我还包括一个基于原始函数trapzf
,以利用approxfun
返回的函数计算积分。
trapzf <- function(x,FUN) trapz(x,FUN(x))
set.seed(2020) # make the results reproducible
a <- rnorm(100,1)
d <- density(a)
f <- approxfun(d$x,d$y)
int1 <- trapz(d$x,d$y^2)
int2 <- trapzf(d$x,function(x) f(x)^2)
int1
#[1] 0.2591226
identical(int1,int2)
#[1] TRUE
,
我认为您应该将目标函数写为function(x) f(x)**2
,而不是f*f
,例如
> integrate (function(x) f(x)**2,min(density(a)$x),max(density(a)$x))
0.2331793 with absolute error < 6.6e-06