[R] readLines with space-delimiter?

kMan kchamberln at gmail.com
Thu May 6 03:53:24 CEST 2010


Dear Seth,

If this were my project, I would likely use something besides readLines().
Have you looked into read.table() or scan()? They'll separate based on your
delimiter on input so you do not need to do post processing.

#example file
txt2<-cbind(c("A","cat","ran","over","the"),c("brown","fox.","","",""))
dfile<-file("test.txt","at")
writeLines(paste(txt[,1], collapse=" "), dfile)
writeLines(paste(txt[,2], collapse=" "), dfile)
close(dfile)

#via scan()
scan("test.txt", sep=" ", what="") # character vector, empty character
strings interpreted
scan("test.txt", sep="\n", what="") # each line (as in readLines())
scan("test.txt", what="") # white space delimited

#untested
x<-scan(datin, what="", nlines=10)

If your forty something columns have known data types other than
character(), setting what=list() with the types (or ignore a column with
NULL as a value) will configure your types on read as well.

txt2<-cbind(c("A","cat","ran","over",5),c("the","brown","fox.","",7)) # all
character after coercion
dfile<-file("test2.txt","at")
writeLines(paste(txt2[,1], collapse=" "),dfile)
writeLines(paste(txt2[,2], collapse=" "),dfile)
close(dfile)

whatl<-list("","","","",0)
names(whatl)<-c("char1","char2","char3","another","numbers")
data.frame(scan("test2.txt", sep=" ", what=whatl))

The rwiki has a page with more detail on scan().
http://rwiki.sciviews.org/doku.php?id=large_scale_data:lsdioi_scangritty

Sincerely,
KeithC.



More information about the R-help mailing list