Filtering table based on row non-zero values in R

huangapple go评论161阅读模式
英文:

Filtering table based on row non-zero values in R

问题

我有一个如下的表格:

  1. 日期 X1 X2 X3
  2. 1/1 0 3 34
  3. 2/1 0 7 65
  4. 3/1 0 13 0
  5. 4/1 25 4 65
  6. 5/1 35 0 0
  7. 6/1 4 6 9
  8. 7/1 0 0 0

我该如何使用 dplyr 只选择在所有X列开始出现非零值之后的行。在这种情况下,只选择日期为 4/15/16/17/1 的行。谢谢。

英文:

I have a table like the following:

  1. date X1 X2 X3
  2. 1/1 0 3 34
  3. 2/1 0 7 65
  4. 3/1 0 13 0
  5. 4/1 25 4 65
  6. 5/1 35 0 0
  7. 6/1 4 6 9
  8. 7/1 0 0 0

How can I use dplyr to select rows only after all Xs start appearing non-zero values. In that case, select only rows for dates 4/1, 5/1, 6/1 and 7/1. Thank you.

答案1

得分: 3

  1. 您可以使用`cumsum` + `rowSums`函数
  1. > subset(df, cumsum(rowSums(df[-1] > 0) == length(df) - 1) > 0)
  2. 日期 X1 X2 X3
  3. 4 4/1 25 4 65
  4. 5 5/1 35 0 0
  5. 6 6/1 4 6 9
  6. 7 7/1 0 0 0
英文:

You can use cumsum + rowSums

  1. > subset(df, cumsum(rowSums(df[-1] > 0) == length(df) - 1) > 0)
  2. date X1 X2 X3
  3. 4 4/1 25 4 65
  4. 5 5/1 35 0 0
  5. 6 6/1 4 6 9
  6. 7 7/1 0 0 0

答案2

得分: 3

  1. df %>%
  2. filter(cumsum(if_all(starts_with('X'), ~.x > 0)) > 0)
  3. date X1 X2 X3
  4. 1 4/1 25 4 65
  5. 2 5/1 35 0 0
  6. 3 6/1 4 6 9
英文:
  1. df %>%
  2. filter(cumsum(if_all(starts_with('X'), ~.x > 0))>0)
  3. date X1 X2 X3
  4. 1 4/1 25 4 65
  5. 2 5/1 35 0 0
  6. 3 6/1 4 6 9
  7. 4 7/1 0 0 0

or even:

  1. df %>%
  2. filter(cumsum(if_all(starts_with('X'))>0)>0)
  3. date X1 X2 X3
  4. 1 4/1 25 4 65
  5. 2 5/1 35 0 0
  6. 3 6/1 4 6 9
  7. 4 7/1 0 0 0

答案3

得分: 2

如果我理解问题正确:

  1. df[apply(apply(df[, -1],
  2. 2, \(col) cumsum(col > 0)),
  3. 1, prod) > 0, ]
  4. # date X1 X2 X3
  5. # 4 4/1 25 4 65
  6. # 5 5/1 35 0 0
  7. # 6 6/1 4 6 9
  8. # 7 7/1 0 0 0
英文:

If I understand the question correctly:

  1. df[apply(apply(df[, -1],
  2. 2, \(col) cumsum(col > 0)),
  3. 1, prod) > 0, ]
  4. # date X1 X2 X3
  5. # 4 4/1 25 4 65
  6. # 5 5/1 35 0 0
  7. # 6 6/1 4 6 9
  8. # 7 7/1 0 0 0

huangapple
  • 本文由 发表于 2023年3月9日 16:50:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定