Filtering table based on row non-zero values in R

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

Filtering table based on row non-zero values in R

问题

我有一个如下的表格:

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

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

英文:

I have a table like the following:

date X1 X2 X3
1/1   0  3 34 
2/1   0  7 65
3/1   0 13  0
4/1  25  4 65
5/1  35  0  0
6/1   4  6  9
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

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

You can use cumsum + rowSums

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

答案2

得分: 3

df %>%
  filter(cumsum(if_all(starts_with('X'), ~.x > 0)) > 0)

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

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

or even:

df %>%
   filter(cumsum(if_all(starts_with('X'))>0)>0)

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

答案3

得分: 2

如果我理解问题正确:

df[apply(apply(df[, -1], 
               2, \(col) cumsum(col > 0)), 
         1, prod) > 0, ]

#   date X1 X2 X3
# 4  4/1 25  4 65
# 5  5/1 35  0  0
# 6  6/1  4  6  9
# 7  7/1  0  0  0
英文:

If I understand the question correctly:

df[apply(apply(df[, -1], 
               2, \(col) cumsum(col > 0)), 
         1, prod) > 0, ]

#   date X1 X2 X3
# 4  4/1 25  4 65
# 5  5/1 35  0  0
# 6  6/1  4  6  9
# 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:

确定