我有一个过去3年的每日股票价格专栏。现在,我想找出价格连续上涨5倍的序列,然后创建一个新列,其中我设置了“buy”。有人能帮我生成这个吗?
这就是我尝试过的,但如果没有太多意义,请道歉,因为我是初学者
x <- FB[,"Close"] if (x<x+1, x+1<x+2, x+2<x+3, x+3<x+4, x+4<5) { FB$buy <- 1 } 发布于 2020-11-07 06:04:18
这篇文章的标签说的是dplyr,所以我将提供一个dplyr方法,而不是一个基本的R方法。这是一种蛮力方法,但应该很容易遵循。
library(dplyr)
FB <- data.frame(
"Close" = c(1,2,3,4,5,6,1,2,3,4,1,2,3,4,5,6),
stringsAsFactors = FALSE
)
# Brute Force dplyr
x <- FB %>%
mutate(buy = Close>lag(Close,1) &
lag(Close,1)>lag(Close,2) &
lag(Close,2)>lag(Close,3) &
lag(Close,3)>lag(Close,4) &
lag(Close,4)>lag(Close,5)
) %>%
# If you really need a 1 instead of a True
mutate(buy = as.numeric(buy)) # %>%
# If there weren't 5 previous the result is NA
# and you can impute something that makes sense
# if anything makes sense.
# mutate(buy = ifelse(is.na(buy),0,buy))
x
# Close buy
# 1 NA
# 2 NA
# 3 NA
# 4 NA
# 5 NA
# 6 1
# 1 0
# 2 0
# 3 0
# 4 0
# 1 0
# 2 0
# 3 0
# 4 0
# 5 0
# 6 1https://stackoverflow.com/questions/64721652
复制相似问题