我的数据是一个时间序列,其中包含Date列和一个介于1和4之间的值序列。我试图找到从1-3或4-2运行的连续值的模式并检索日期模式完成(即,在第一个场景中击中3,在第二个场景中击中2)。
输入数据如下:
data.frame(Date=seq(as.Date("2010/1/1"), as.Date("2010/1/20"), "day"),
Value=c(1,2,3,4,3,4,3,4,3,2,1,2,1,2,3,4,3,4,3,2))
Date Value
1 2010-01-01 1
2 2010-01-02 2
3 2010-01-03 3
4 2010-01-04 4
5 2010-01-05 3
6 2010-01-06 4
7 2010-01-07 3
8 2010-01-08 4
9 2010-01-09 3
10 2010-01-10 2
...
我想要的输出是,例如:
data.frame(Date=as.Date(c("2010/1/3","2010/1/10","2010/1/15","2010/1/20")),
Value=c("Win","Loss","Win","Loss"))
Date Value
2010-01-03 Win
2010-01-10 Loss
2010-01-15 Win
2010-01-20 Loss
前一序列(Win)可以与后者(损失)区分开来。
非常感谢!
答案 0 :(得分:1)
显然,有多种方法可以做到这一点:
#' @param d a vector of dates
#' @param v a vector of numeric values
win_lose <- function(d,v) {
l <- list()
for (i in 3:length(v)) {
if (v[i] == 3 & v[i-1] == 2 & v[i-2] == 1) {
l[[length(l)+1]] <- data.frame(Date= d[i], Value= "Win")
} else if (v[i] == 2 & v[i-1] == 3 & v[i-2] == 4) {
l[[length(l)+1]] <- data.frame(Date= d[i], Value= "Loss")
}
}
return(data.frame(do.call("rbind", l)))
}
R> win_lose(df$Date, df$Value)
Date Value
1 2010-01-03 Win
2 2010-01-10 Loss
3 2010-01-15 Win
4 2010-01-20 Loss
答案 1 :(得分:1)
你可以通过序列匹配来做到这一点。假设你的数字不超过9.基本的想法是从你的Value变量中创建一个字符串序列。然后搜索你的&#34; win&#34;的结束索引。和&#34;损失&#34;序列(即123或432)。
library(stringr)
sequence <- paste(df$Value, collapse = "")
wins <- str_locate_all(sequence, "123")
losses <- str_locate_all(sequence, "432")
dfwin <- df[wins[[1]][,2],]
dfwin$Value <- "Win"
dfloss <-df[losses[[1]][,2],]
dfloss$Value <- "Loss"
rbind(dfwin,dfloss)
Date Value
3 2010-01-03 Win
15 2010-01-15 Win
10 2010-01-10 Loss
20 2010-01-20 Loss