Peng Peng
Peng Peng

Reputation: 1365

Manipulating a file in R

In Python:

fo = open("foo.txt", "r+")  
str = fo.read(10);  
position = fo.tell();  
print "Current file position : ", position  

Is there a file pointer in R? Can I know where the current file position is while I read the file?

Upvotes: 1

Views: 131

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56935

Well to look at file-related functions you can try ?file which tells you how to open a file and many file-related functions.

fo <- file('foo.txt', 'r+') // see  ?file for more details on the parameters

fo is a connection object that can be fed to other functions. I recommend you read all of ?file, which is very informative.

In particular, see the See Also and Examples sections.

In the See Also section are listed a set of related functions for working with files. In here it mentions (for example) readLines, readBin (to read binary files), scan (to read data into a vector or list) for reading files.

It also mentions seek. Looking at ?seek you will see that

seek with where = NA returns the current byte offset of a connection (from the beginning)

So try

seek(fo)

(Tip - the help files in R are very helpful! The 'See Also' section will tell you functions related to the one you are looking at, and the 'Examples' section will give you examples of how to use them. If you wanted to look up stuff to do with files and ?file didn't work, you could always do ??file which does a fuzzy search).

Upvotes: 3

Related Questions