【问题标题】:Extracting subsets of data提取数据子集
【发布时间】:2010-12-28 06:04:52
【问题描述】:

这似乎真的是一项容易的任务,但是对于编程世界来说是全新的,我对以下任务有疑问: 我有一个大文件,格式如下:

track type= wiggle name09
variableStep chrom=chr1
34 5 
36 7 
54 8 
variableStep chrom=chr2 
33 4 
35 2 
78 7 
this is text with the word random in it# this we need to remove
82 4 
88 6 
variableStep chrom=chr3 
78 5 
89 4 
56 7

现在我想要的只是输出

一个名为 1 的文件 并且只包含

34 5
36 7
54 8

a second file called 2

33 4
35 2
78 7
82 4 
88 6

a third file

78 5
89 4
56 7

如果能在这方面获得一些帮助会很棒... 如果有人知道如何在 R 中做到这一点......那就更好了

【问题讨论】:

  • sometext_sometext 是否以数字开头?
  • no... 格式为 variableStep chrom=chr1 data data data variableStep chrom=chr2 data data ...
  • 实际上会一直到 chr22 然后继续 chrx。
  • 给出一个实际的样本,不要猜测......

标签: regex perl parsing r


【解决方案1】:

这是 R 中的一个解决方案。

加载您的数据:

a <- readLines(textConnection("track type= wiggle name09
variableStep chrom=chr1
34 5 
36 7 
54 8 
variableStep chrom=chr2 
33 4 
35 2 
78 7 
this is text with the word random in it# this we need to remove
82 4 
88 6 
variableStep chrom=chr3 
78 5 
89 4 
56 7"))

通过查找断点并仅保留具有数字空间数字格式的行来处理它:

idx <- grep("=", a)
idx <- idx[c(which((idx[-1]-idx[-length(idx)])>1),length(idx))]
idx <- cbind(idx+1,c(idx[-1]-1,length(a)))
sapply(1:nrow(idx), function(i) {
    x <- a[idx[i,1]:idx[i,2]]
    write.table(x[grep("^\\d+\\s+\\d+\\s*", x, perl=TRUE)], file=as.character(i), row.names=FALSE, col.names=FALSE, quote=FALSE)
})

【讨论】:

  • 嗨 Shane,它会写到哪里?我通常在使用 write.table 时指定一个目录
  • 除了第一块数据(1)之外,代码给出了有趣的结果,混合数据并将文本留在里面
  • 嗨 Shane,它不太工作,现在它只返回没有数据的第一行?不过它确实有作用......感谢您抽出宝贵的时间
  • 嗯,它适用于您的示例数据。如果没有更多信息,不知道该告诉您什么。
  • 使用与艾伦的解决方案相同的正则表达式再次更新。
【解决方案2】:

以下有帮助吗?

#!/usr/bin/env perl

use strict;
use warnings;

my $filename = 1;
my $flag;
my $fh;

while (<>) {
    if (/^\d+\s+\d+\s*$/) {
        if ( $flag == 1 ) {
            $flag = 0;
            open $fh, '>', $filename;
            $filename++;
        }
        print $fh $_;
    }
    elsif (/random/) {
        next;
    }
    else {
        $flag = 1;
    }
}

用法:

将以上内容另存为extract(或任何其他名称,如果重要的话)。

假设有数据的文件名为file

perl extract /path/to/file

【讨论】:

  • 一个编程新手可能需要一些关于如何使用 Perl 脚本的说明...
  • 也许...我不懂正则表达式...不过让我试试...谢谢
  • @las3rjock:更新了答案。
  • @Tamir:正则表达式检查该行是否以数字开头,然后有一些空格,然后再次数字到行尾。如果是这样,我们将该行写入文件。
  • 酷!!!有用!一些小事...命名错误...基本上它调用文件 1 文件 2 等等。其次,在数据块中,我需要先删除单行文本,然后才能使用上面的脚本......它们都是不同的,但它们共享“随机”这个词出现在每个文本中跨度>
猜你喜欢
  • 2011-04-18
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
相关资源
最近更新 更多