在r中应用特定条件和滚动窗口的移动平均线


df <- structure(
list(
inv = c("INV_1", "INV_1", "INV_1", "INV_1", "INV_1", "INV_2", "INV_2", "INV_2", "INV_2", "INV_2", "INV_2"),
ass = c("x", "x", "x", "y", "y", "x", "x", "x", "t", "t", "t"),
datetime = c("2010-01-01", "2010-01-02", "2010-01-03", "2010-01-08", "2010-01-19", "2010-02-20", "2010-02-22", "2010-02-23", "2010-03-01", "2010-03-02", "2010-03-04"),
price = c(10, 10, 19, 9, 3 , 5, 1, 4, 4, 5, 1),
operation = c(10, 0, 2, 2, 0, 5, 5, 5, 3, 0, 2)
),
class = "data.frame", row.names = c(NA, -11L)
)

我有这个数据框,我想计算"价格"的移动平均线。列。

在此之前,我特别需要应用一个小的更改。我想更改一下"价格"。列值,如果"操作";值等于0

因此我需要R:

df <- df %>% mutate( price = if_else(operation == 0, NA, price)

然后当price == NA用价格列的移动平均线填充值。由于我可以在价格列中有连续的na,我认为移动平均线应该与滚动窗口一起应用。

我是一个新的R用户,所以我不知道怎么做。任何想法?如果可能的话,我更喜欢dplyr解决方案

假设目的是计算从开始到当前行的修改价格的平均值,去掉0行,以便从平均值中消除它们。例如,第三行应该使用10和19的平均值,即14.5。

代码指定了n()(=行数)元素的平均值,但是partial=TRUE指示它只在有更少的情况下使用有多少元素。na。rm=TRUE导致NA不包含在平均值中。我们已经从dplyr中排除了filter和lag,因为它们会破坏R中同名的函数,因此往往会导致难以检测的错误。如果您需要使用它们,请使用dplyr::lag和dplyr::filter。

library(dplyr, exclude = c("filter", "lag"))
library(zoo)
df %>% 
mutate(price = ifelse(operation == 0, NA, price),
avg = rollapplyr(price, n(), mean, na.rm = TRUE, partial = TRUE))

这个变化也是有效的。1:n()指定I个元素应该用于第I行。再次,na。rm=TRUE将从计算中剔除NA。

df %>%
mutate(price = ifelse(operation == 0, NA, price),
avg = rollapplyr(price, 1:n(), mean, na.rm = TRUE))

如果目的是用前一行的平均价格改变价格,其中操作>0;下面是我的dplyr代码。

df <- tibble(df)

df %>% 
mutate( price = ifelse( operation==0, 0 ,price)) %>% 
mutate(runinngsumPrice = cumsum(price))  %>% 
mutate(runinngsumNNA = cumsum(ifelse(operation==0,0,1)))  %>% 
mutate( price = ifelse( operation==0, runinngsumPrice/runinngsumNNA ,price))  %>% 
select(1:5)

# 
#   # A tibble: 11 x 5
#   inv   ass   datetime   price operation
#   <chr> <chr> <chr>      <dbl>     <dbl>
#     1 INV_1 x     2010-01-01 10           10
#   2 INV_1 x     2010-01-02 10            0
#   3 INV_1 x     2010-01-03 19            2
#   4 INV_1 y     2010-01-08  9            2
#   5 INV_1 y     2010-01-19 12.7          0
#   6 INV_2 x     2010-02-20  5            5
#   7 INV_2 x     2010-02-22  1            5
#   8 INV_2 x     2010-02-23  4            5
#   9 INV_2 t     2010-03-01  4            3
#   10 INV_2 t     2010-03-02  7.43         0
#   11 INV_2 t     2010-03-04  1            2

最新更新