Smith Black
Smith Black

Reputation: 535

How to read specific lines into R?

I want to read a set of specific lines specified by indices from a txt file into R, for example

index = c(2, 5, 9, 99, 100)

meaning the 2nd, fifth, etc lines into R. How should I approach this? Shall I use

scan (file, skip = index[i]-1, nlines = 1)

with a for loop?

Upvotes: 2

Views: 2119

Answers (2)

Federico Giorgi
Federico Giorgi

Reputation: 10735

lapply does not work in my case (R version 4.1), returning always the same line (number one).

The proposed loop works. Here is a working example.

lines<-c(3,5,900,1000)
items<-c()
for(i in 1:length(lines)){
    item<-scan(file,skip=lines[i]-1,nlines=1)
    items<-c(items,item)
}

Upvotes: 1

Ricardo Saporta
Ricardo Saporta

Reputation: 55350

use lapply:

lns <- lapply(index, function(i) <your scan line>) 

do.call(rbind, lns)

# or
data.table::rbindlist(lns)

Upvotes: 2

Related Questions