【发布时间】:2020-09-01 00:51:49
【问题描述】:
我需要编写一个函数来平滑向量而不丢失向量值的原始等级顺序。我想出的是以下内容:
#1 Sort all values of vector in ascending order
#2 for the kth value in vector s_k in the ordered list, collect the list of 2N+1 values in the window of values between [s_{k-N}, s_{k+N}]
#3 by definition, s_k is the median of the values in that window
#4 replace s_k with the mean of value in that same window for all values of k
理想情况下,我希望能够编写一个依赖于dbplyr 的函数,因为我正在处理远程数据,但这不是绝对必要的,因为我可以将数据分成块,所以基本 R 是可以的也。同样,这也可以是所有 postgressql 代码或部分 sql 部分dbplyr,它是一样的,但有一些要求。我需要能够参数化N 并且我需要能够为函数提供数据帧列表或表集(如果在数据库中)以循环遍历(在 R 中这很简单,一个具有单个参数的函数对于 N 在 lapply 包装器内)。
这是我迄今为止为N=3 得到的:
#Example Data
s <- rnorm(1000, mean=50, sd=10)
test.in <- as.data.frame(s)
test.in$id <- 1:length(s)
#Non parameterized attempt
test.out <- test.in %>%
rename(s = union_v_corporate_candidate) %>%
mutate(lag_k_3 = lag(s, 3),
lead_k_3 = lead(s, 3),
lag_k_2 = lag(s, 2),
lead_k_2 = lead(s, 2),
lag_k_1 = lag(s, 1),
lead_k_1 = lead(s, 1)) %>%
mutate(window_mean = (lag_k_3 + lead_k_3 + lag_k_2 + lead_k_2 + lag_k_1 + lead_k_1 + s)/7) %>%
select(id, s, window_mean)
上述方法的逻辑问题是我无法参数化N,因为每个额外的N 值都需要两个额外的mutate 子句。
【问题讨论】:
标签: r postgresql dplyr smoothing dbplyr