【发布时间】:2019-02-04 01:05:43
【问题描述】:
这些问题与我自己的主题类似 calculation of 90 percentile and replacement of it by median by groups in R
有了这个区别。
但是,在那个话题中 请注意,计算是由一类动作之前的 14 个零完成的,但对于所有零类动作并用中位数替换,并为每个组代码+项目执行
也就是说,现在我使用全零而不是前面的 14,并且不要触及返回的负值和零值。
通过 Zero 类别的组变量 (action- 0, 1),我想通过返回变量找到 75 个百分位,如果值超过 75 个百分位,则必须将其替换为 zero 类别的中位数。所以有code变量这个过程必须对代码单独执行。注意:负值和零值我不碰
mydat=structure(list(code = c(123L, 123L, 123L, 123L, 123L, 123L, 123L,
123L, 123L, 123L, 123L, 123L, 124L, 124L, 124L, 124L, 124L, 124L,
124L, 124L, 124L, 124L, 124L, 124L), action = c(0L, 0L, 0L, 0L,
0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 1L, 1L, 1L), return = c(-1L, 0L, 23L, 100L, 18L, 15L, -1L,
0L, 23L, 100L, 18L, 15L, -1L, 0L, 23L, 100L, 18L, 15L, -1L, 0L,
23L, 100L, 18L, 15L)), .Names = c("code", "action", "return"), class = "data.frame", row.names = c(NA,
-24L))
\
23
100
18
15
如何获得该输出。所以 75 个百分位:
42,25 中位数=20,5 替换
add action return
123 0 -1
123 0 0
123 0 23
123 0 ***20,5
123 0 18
123 0 15
123 1 -1
123 1 0
123 1 23
123 1 100
123 1 18
123 1 15
124 0 -1
124 0 0
124 0 23
124 0 ***20,5
124 0 18
124 0 15
124 1 -1
124 1 0
124 1 23
124 1 100
124 1 18
124 1 15
使用最大的 Uwe 解决方案,我得到了错误
Error in `[.data.table`(mydat[action == 0, `:=`(output, as.double(return))], :
Column(s) [action] not found in i
如何处理我不接触的负值和零值以及发生此错误的原因。
library(data.table)
# mark the zero acton rows before the the action period
setDT(mydat)[, zero_before := cummax(action), by = .(code)]
# compute median and 90% quantile for that last 14 rows before each action period
agg <- mydat[zero_before == 0,
quantile(tail(return), c(0.5, 0.75)) %>%
as.list() %>%
set_names(c("med", "q90")) %>%
c(.(zero_before = 0)), by = .(code)]
agg
# append output column
mydat[action == 0, output := as.double(return)][
# replace output values greater q90 in an update non-equi join
agg, on = .(code,action, return > q90), output := as.double(med)][
# remove helper column
, zero_before := NULL]
【问题讨论】:
标签: r dplyr data.table plyr