> tf <- tempfile()
> cat(c("a,b", "1,2", "3,4", "5,,6", "7,8"), file=tf, sep="\n")
> # following will fail
> read.table(tf, sep=",", header=TRUE)
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
line 1 did not have 3 elements
> # following reads lines with 2 fields only
> textLines <- readLines(tf)
> counts <- count.fields(textConnection(textLines), sep=",")
> read.table(textConnection(textLines[counts == counts[1]]), header=TRUE, sep="\t")
a b
1 1 2
2 3 4
3 7 8
Just a collection of some random cool stuff. PS. Almost 99% of the contents here are not mine and I don't take credit for them, I reference and copy part of the interesting sections.
Friday, July 6, 2012
How to ignore lines when reading files in R
https://stat.ethz.ch/pipermail/r-help/2012-January/301518.html
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment