[R] read a file of text with read.table

Rolf Turner r.turner at auckland.ac.nz
Thu Jun 26 10:39:09 CEST 2014


On 26/06/14 19:32, carol white wrote:

> It might be a primitive question

All questions are primitive; some questions are more primitive than others.

> but I have a file of text and there
> is no separator between character on each line and the strings on
> each line have the same length. The format is like the following
> absfjdslf
> jfdldskjff
> jfsldfjslk
>
> When I read the file with read.table("myfile",colClasses =
> "character"), instead of putting the strings in a table of number of
> rows x length of string, read.table saves the file in a table of
> number of rows x 1 and each element seems to be a factor. Why does
> read.table not account for  colClasses = "character"?

(1) You might try setting stringsAsFactors=FALSE rather than
colClasses = "character".

(2) Since your "table" has only one column you might as well use scan() 
(with what="") and save wear and tear on the system.

(3) In your example the strings do *not* have the same length; the first 
has 9 characters, the next two have 10 each.

(4) Do you want to get a data frame each column of which is a single 
character?  This was not clear from your email.  Do you know how to do 
this?  (It's easy --- when the string lengths are indeed all the same.)
I appended a "g" to the first string and did:

ttt <- scan("temp.txt",what="")
sss <- strsplit(ttt,"")
rrr <- as.data.frame(do.call(rbind,sss))
rrr
   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  a  b  s  f  j  d  s  l  f   g
2  j  f  d  l  d  s  k  j  f   f
3  j  f  s  l  d  f  j  s  l   k

Is this what you want?

cheers,

Rolf Turner



More information about the R-help mailing list