Reading a dat file in R

Viewed 7989

I am trying to read a dat file with ";" separated. I want to read a specific line that starts with certain characters like "B" and the other line are not the matter of interest. Can anyone guide me.

I have tried using the read_delim, read.table and read.csv2.But since some lines are not of equal length. So, I am getting errors.

file <- read.table(file = '~/file.DAT',header = FALSE, quote = "\"'",dec = ".",numerals = c("no.loss"),sep = ';',text)

I am expecting a r dataframe out of this file which I can write it to a csv file again.

1 Answers

You should be able to do that through readLines

allLines <- readLines(con = file('~/file.DAT'), 'r')
grepB <- function(x) grepl('^B',x)
BLines <- filter(grepB, allLines)
df <- as.data.frame(strsplit(BLines, ";"))

And if your file contains header, then you can specify

names(df) <- strsplit(allLines[1], ";")[[1]]
Related