[英]R custom running function
How can I achieve same results without loop? 如何在不循环的情况下获得相同的结果? It's equivalent of scan function in reactiveX but with custom logic ( http://reactivex.io/rxjs/img/scan.png )
它等效于reactX中的扫描功能,但具有自定义逻辑( http://reactivex.io/rxjs/img/scan.png )
for (i in 2:nrow(x)) {
x$running_number[i] <-
ifelse(abs(x$running_number[(i - 1)] - x$numbers[i]) > max_diff,
x$numbers[i],
x$running_number[(i - 1)])
}
EDIT: 编辑:
Not sure I asked correctly after your reply. 不确定您的回覆后我是否正确询问。 Take a look at this dataframe
看看这个数据框
x <- data.frame(
c(1000, 1010, 1020, 1030, 1100, 1120, 1140, 1150, 1200),
c(1000, 1000, 1000, 1000, 1100, 1100, 1100, 1100, 1200)
)
colnames(x) <- c('input_v', 'output_v')
Given x$input_v need to get x$output_v 给定x $ input_v需要获取x $ output_v
I can express condition like : 我可以表达以下条件:
x$output_v <-
ifelse(
abs(x$input_v - somehow_get_me_last_assigned_x_output_v) > 90,
x$input_v,
somehow_get_me_last_assigned_x_output_v
)
We can use diff
to find the difference between the adjacent elements, create the logical condition with 'max-diff', use that in ifelse
to return either the 'numbers' or the lag
of 'running_number' 我们可以使用
diff
来找到相邻元素之间的差异,使用'max-diff'创建逻辑条件,在ifelse
使用它来返回'数字'或'running_number'的lag
with(x, ifelse(c(FALSE, abs(diff(running_number)) > max_diff),
numbers, c(NA, running_number[-nrow(x)])))
Or with dplyr
或与
dplyr
library(dplyr)
x %>%
mutate(running_number = case_when(c(FALSE, abs(diff(running_number)) >
max_diff)0 ~ numbers, TRUE ~ lag(running-number)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.