how to read from R a .txt file with two lines for each case. For example a file like [ http://www.amstat.org/publications/jse/datasets/93cars.dat.txt ] Please help. CL
Asked
Active
Viewed 711 times
2 Answers
0
I think this is the simplest way I can think of. And you should note that your URL link in the question includes the square bracket, which might slow folks down.
u <- url("http://www.amstat.org/publications/jse/datasets/93cars.dat.txt")
d <- readLines(u)
s <- paste(d[seq(1,length(d),2)], d[seq(2,length(d),2)])
data <- read.table(header=F, stringsAsFactors=F, text=s)

Forrest R. Stevens
- 3,435
- 13
- 21
-
Hi, Forrest I appreciate your help. Sorry about the ]. – user2203706 May 14 '15 at 04:16
0
There are many other ways to do this, and indeed this question is an exact duplicate of the question here (same question, same data), which has an answer using read.fwf
which requires you to know the fixed-width of each field. This can be automated but perhaps cumbersome.
The most scalable way, at least on POSIX machines is to use command line tools like awk
to do the pre-processing efficiently and quickly for you. Here is an example using awk
that reads the file in two parts (alternate rows) and cbind
s them together.
download.file("http://www.amstat.org/publications/jse/datasets/93cars.dat.txt",
destfile = "Data/93cars.txt")
firstPart = pipe(description = "awk 'NR%2==0' < Data/93cars.txt")
secondPart = pipe(description = "awk 'NR%2 != 0' < Data/93cars.txt")
dfCars = cbind(read.table(firstPart), read.table(secondPart))

Community
- 1
- 1

tchakravarty
- 10,736
- 12
- 72
- 116