Analysis of the main input file in R

I'm used to perl and new to R. I know that you can read whole tables with read.table(), but I wonder how I can use R to parse a single line from an input file.

In particular, which is equivalent to the following perl snippet:

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

As in the previous example:

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]

, , , , , , , , , ( , Perl ).

readLines ( 1) strsplit , Perl.

R , Perl ( , ).

+3

, scan, , readLines strsplit s, grep ..

:

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

Just to show another way to do this (if your input is "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)

I assume that the most important part above in terms of resolving your issue is simply

nrows=1

which tells him to parse one line of input. (Under read.csv in the end it just calls down to scan.)

0
source

All Articles