我正在尝试编写一个计算新近度加权平均值的函数。我的第一步是计算权重。我正在使用e ^ -t(其中e =自然对数或exp(1))。我已经写了一个计算函数,但是得到的结果不正确。我已经在reprex中提供了我的代码。
library(tidyverse)
library(lubridate)
library(reprex)
dat <- tibble (d = c( ymd('20170625'), ymd('20170524'), ymd('20170420')))
rwtm <- function(date,max,den){
wt <- map_dbl(date, ~ sum(((-((as.double((.x-date)* between(as.numeric(difftime(.x, date, units = "days")), 1e-9, max))/den))))))
}
rwtmexp <- function(date,max,den){
wt <- map_dbl(date, ~ sum((exp(-((as.double((.x-date)* between(as.numeric(difftime(.x, date, units = "days")), 1e-9, max))/den))))))
}
dat %>%
mutate(test = rwtm(d,32,75) ) %>%
mutate(exp_test = rwtmexp(d,32,75))
#> # A tibble: 3 x 3
#> d test exp_test
#> <date> <dbl> <dbl>
#> 1 2017-06-25 -0.427 2.65
#> 2 2017-05-24 0 3
#> 3 2017-04-20 0 3
由reprex package(v0.3.0)在2020-05-15创建
我的预期结果如下:
2017 -06-25 | -0.427 | 0.6526
2017-05-24 | 0 | 1
2017-04-20 | 0 | 1
其中exp(-0.427)= 0.6526和exp(0)= 1
注意,函数rwtm和rwtmexp之间的唯一区别是exp函数的插入。这似乎是我的计算出错的地方。
exp
可以包裹整个表达式
library(purrr)
library(dplyr)
rwtmexp <- function(date,max,den){
wt <- map_dbl(date, ~ exp(sum((-((as.double((.x-date)*
between(as.numeric(difftime(.x, date, units = "days")),
1e-9, max))/den))))))
}
dat %>%
mutate(test = rwtm(d,32,75) ) %>%
mutate(exp_test = rwtmexp(d,32,75))
# A tibble: 3 x 3
# d test exp_test
# <date> <dbl> <dbl>
#1 2017-06-25 -0.427 0.653
#2 2017-05-24 0 1
#3 2017-04-20 0 1