【问题标题】:Basic input file parsing in RR中的基本输入文件解析
【发布时间】:2011-04-08 05:41:00
【问题描述】:

我习惯了 perl 和 R 新手。我知道您可以使用 read.table() 读取整个表,但我想知道如何使用 R 解析输入文件中的单行。

具体来说,相当于下面的perl sn -p:

open my $fh, $filename or die 'can't open file $filename';
my $line = <$fh>;
my ($first, $second, $third) = split ("\t", $line);

【问题讨论】:

    标签: perl parsing file r


    【解决方案1】:

    与上述类似的是:

    filename <- 'your/file/name/here'
    fh <- file( filename, open='rt' )
    line <- readLines(fh, n=1 )
    tmp <- strsplit(line, "\\t")
    first <- tmp[[1]][1]; second <- tmp[[1]][2]; third <- tmp[[1]][3]
    

    file函数创建一个到文件的连接并打开它,打开是可选的,但是如果你不打开文件,那么当你从它读取时它会打开然后再次关闭文件,如果你打开文件然后它保持打开状态,下一次读取从前一次离开的位置继续(最接近 Perl 将在上面执行的操作)。

    readLines 函数将读取指定的行数(本例中为 1) 那么 strsplit 的工作原理与 Perl 的 split 函数基本相同。

    R 没有像 Perl 那样的多重赋值(通常最好还是将结果放在一起,而不是拆分成多个全局变量)。

    【讨论】:

    • 一个警告——这会将整个文件加载到内存中并拆分其所有行。如果文件很大并且您只需要前三个元素,这肯定不是一个好主意。
    • 对于小文件,它可能会读取整个内容,但对于较大的文件,它只会将部分内容读入内存,当您继续从文件中读取时,它会抓取额外的块。
    【解决方案2】:

    通常,您应该使用scan 来执行此操作,或者在更复杂的情况下,使用readLines 读取整个文件并使用strsplits、greps 等手动解析它。

    在你的情况下:

    scan(filename,character(0),nmax=3)->d
    first<-d[1];d[2]->second;third<-d[3]
    

    【讨论】:

      【解决方案3】:

      只是为了展示另一种方法(假设您的输入是“temp/3.txt”):

      > d <- read.csv("temp/3.txt", sep="\t", stringsAsFactors=F, header=F, nrows=1)
      # Show the default column names:
      > colnames(d)
      [1] "V1" "V2" "V3"
      # Assign the requested column names
      > colnames(d) <- c("first", "second", "third")
      # Show the current structure of d
      > d
        first second third
      1     1      2     3
      # Probably not recommended: Add the columns of d to the search path
      > attach(d)
      > first
      [1] 1
      # Clean up:
      > detach(d)
      

      我想就解决您的问题而言,上面最重要的部分只是

      nrows=1
      

      告诉它解析一行输入。 (在 read.csv 下面最终只是调用扫描。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-10
        相关资源
        最近更新 更多