子集行 + 上下文 [英] subset rows + context

查看:28
本文介绍了子集行 + 上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直无法找到一种简单的方法来在我想要选择的行周围包含一些上下文(n 个相邻的行).
我或多或少地尝试镜像 grep 的 -C 选项来选择 data.frame 的某些行.

I haven't been able to figure out an easy way to include some context ( n adjacent rows ) around the rows I want to select.
I am more or less trying to mirror the -C option of grep to select some rows of a data.frame.

例如:

a= data.frame(seq(1:100))  
b = c(50, 60, 61)

假设我想要在 b 中索引的行周围有 2 行的上下文;所需的输出应该是 a 的数据框子集,行数为 48,49,50,51,52,58,59,60,61,62,63

Let's say I want a context of 2 lines around the rows indexed in b; the desired output should be the data frame subset of a with the rows 48,49,50,51,52,58,59,60,61,62,63

推荐答案

您可以这样做,但可能有更优雅的方法来计算索引:

You can do something like this, but there may be a more elegant way to compute the indices :

a= data.frame(seq(1:100))  
b = c(50, 60, 61)
context <- 2
indices <- as.vector(sapply(b, function(v) {return ((v-context):(v+context))}))
a[indices,]

给出:

 [1] 48 49 50 51 52 58 59 60 61 62 59 60 61 62 63

正如@flodel 指出的,如果索引可能重叠,您必须添加以下行:

EDIT : As @flodel points out, if the indices may overlap you must add the following line :

indices <- sort(unique(indices))

这篇关于子集行 + 上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆