使用"连胜"获取data.frame中的值。 > 2

时间:2015-12-01 14:27:21

标签: r

我有以下df(我的实际df更大,但这更好解释)

df
    Date   Team Result
1 20-10-2014  Bulls      W
2 20-11-2014  Bulls      W
3 21-11-2014  Bulls      W
4 22-10-2014  Bulls      L
5 23-10-2014  Bulls      L
6 24-10-2014  Bulls      W
7 25-10-2014  Bulls      W
8 26-10-2014  Bulls      L

我用rle来计算连胜条件

df$Result <- as.character(df$Result)
result.rle <- rle(df$Result)

最大条纹数量

sort(w.rle$lengths, decreasing = TRUE)

我现在要做的是用2以上的连胜来过滤相关的比赛。

我检查了?rle,但无法找到我要找的东西。有关如何做到这一点的任何想法?

我的最终结果应该是:

#winning streak > 2
        Date   Team Result
1 20-10-2014  Bulls      W
2 20-11-2014  Bulls      W
3 21-11-2014  Bulls      W

2 个答案:

答案 0 :(得分:4)

这是使用data.table::rleid函数

的可能解决方案
library(data.table) # V 1.9.6+
setDT(df)[, indx := .N, by = rleid(Result)][Result == "W" & indx > 2]
#          Date  Team Result indx
# 1: 20-10-2014 Bulls      W    3
# 2: 20-11-2014 Bulls      W    3
# 3: 21-11-2014 Bulls      W    3

另一种选择是破解by声明,以便我们可以在同一个调用中重复使用Result列(而无需单独创建indx

df[, .SD[.N > 2 & Result == "W"], by = rleid(df[["Result"]])]
#    rleid       Date  Team Result
# 1:     1 20-10-2014 Bulls      W
# 2:     1 20-11-2014 Bulls      W
# 3:     1 21-11-2014 Bulls      W

答案 1 :(得分:1)

使用df[intersect(which(rep(rle(df$Result)$lengths,rle(df$Result)$lengths)>2),which(rep(rle(df$Result)$values,rle(df$Result)$lengths)=='W')),] # Date Team Result # 1 20-10-2014 Bulls W # 2 20-11-2014 Bulls W # 3 21-11-2014 Bulls W 的解决方案:

df <- structure(list(Date = c("20-10-2014", "20-11-2014", "21-11-2014", 
"22-10-2014", "23-10-2014", "24-10-2014", "25-10-2014", "26-10-2014"
), Team = c("Bulls", "Bulls", "Bulls", "Bulls", "Bulls", "Bulls", 
"Bulls", "Bulls"), Result = c("W", "W", "W", "L", "L", "W", "W", 
"L")), .Names = c("Date", "Team", "Result"), class = "data.frame", row.names = c(NA, 
-8L))

数据:

rle(df$Result)

rle(df$Result)$lengths返回两个元素的列表:重复次数和重复值。我们复制长度(我们可以使用intersect)来获得与df行数相同的向量。然后我们选择具有重复&gt;的行。 2。

which(rep(rle(df$Result)$values,rle(df$Result)$lengths)=='W') # [1] 1 2 3 6 7 # Those are the rows where it's a Win. Only those rows can be included which(rep(rle(df$Result)$lengths,rle(df$Result)$lengths)>2) # [1] 1 2 3 # those are the rows where it's a streak of 3 wins or losses 取行的索引的交集:

  • 有一个&gt; 2条纹
  • 这是连胜

详细说明:

    H2S 1.4
    C1  3.6

交叉点将给出预期的输出。