【问题标题】:Subset and filter a dataframe by logical operators and select the foregoing rows通过逻辑运算符对数据帧进行子集和过滤,并选择上述行
【发布时间】:2021-09-06 23:50:35
【问题描述】:

我有以下“随机”数据框,想应用基于逻辑运算符的子集,然后想提取上述行:

set.seed(3)
Sample_Data <- data.frame(A = c(1:100, 1:100, 1:100), B = c(100:1, 100:1, 100:1))
print(Sample_Data)
Test_subset <- subset(Sample_Data, subset = A == 1 & B == 100)
Test_subset
    A   B
1   1 100
101 1 100
201 1 100

用逻辑运算符制作子集是没有问题的。 但现在我想知道是否可以在 R 中创建以下过滤器:“使用以下条件过滤所有行(见上文),并在相应过滤的行前面输出 10 行。” 有谁知道这个的解决方案吗?

【问题讨论】:

  • 如何选择“第 1 行前面的 10 行”?

标签: r subset logical-operators


【解决方案1】:

如评论中所述,过滤不存在​​的行(在第 1 行之前没有)是没有意义的。因此,这里有一个参数略有不同的过滤解决方案。假设您要过滤 A == 11 &amp; B == 90 的目标行(此值组合在您的数据中也出现 3 次),并且您希望获得目标行之前的五行。您可以先定义一个函数来获取相关行的索引:

Sequ <- function(col1, col2) {
  # get row indices of target row with function `which`
  inds <- which(col1 == 11 & col2 == 90) 
  # sort row indices of the rows before target row AND target row itself
  sort(unique(c(inds-5, inds-4, inds-3,inds-2, inds-1, inds)))
}

接下来你可以使用这个函数作为slice的输入:

library(dplyr)
Sample_Data %>%
  slice(Sequ(col1 = A, col2 = B))
    A  B
1   6 95
2   7 94
3   8 93
4   9 92
5  10 91
6  11 90
7   6 95
8   7 94
9   8 93
10  9 92
11 10 91
12 11 90
13  6 95
14  7 94
15  8 93
16  9 92
17 10 91
18 11 90

【讨论】:

  • 那个函数解决了我的问题,谢谢! P.S.:是的,我的方法对这里选择的数据集和我选择的过滤器选项没有意义,我没有考虑过
  • 如果它解决了您的问题,为什么不接受答案或至少支持它?
  • 因为我的声望太低 :( “感谢您的反馈!您需要至少 15 声望才能投票,但您的反馈已被记录。” 当我投票时,这就是我得到的你的答案
【解决方案2】:

您可以添加一个带有行号的列来简化此过程。

Sample_Data$row <- seq(nrow(Sample_Data))
Test_subset <- subset(Sample_Data, subset = A == 1 & B == 100)
Test_subset

#    A   B row
#1   1 100   1
#101 1 100 101
#201 1 100 201

对于上述子集中的每一行,选择接下来的 10 行。

result <- Sample_Data[unique(c(t(outer(Test_subset$row, 0:10, `+`)))), ]
result

#     A   B row
#1    1 100   1
#2    2  99   2
#3    3  98   3
#4    4  97   4
#5    5  96   5
#6    6  95   6
#7    7  94   7
#8    8  93   8
#9    9  92   9
#10  10  91  10
#11  11  90  11
#101  1 100 101
#102  2  99 102
#...
#...

【讨论】:

  • 谢谢,这个答案也很好的解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
相关资源
最近更新 更多