1

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

IRTFM
  • 258,963
  • 21
  • 364
  • 487

2 Answers2

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
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 cbinds 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