Skip specific lines using read.csv in R

I want to skip the 1st and 3rd lines of my csv file when importing a file into a data frame in R.

In the source file, my headers are on line 2.

Using the skip argument in read.csv I can skip the 1st line and set the argument to the TRUE header, I still have the 3rd line from the source file in my data frame.

Can anyone suggest how to skip a few specific lines in R, below is what I was able to put together?

Can I pass a vector into a skip argument specifying the exact lines to ignore?

prach <- read.csv("RSRAN104_-_PRACH_Propagation_Delay-PLMN-day-rsran_RU50EP1_reports_RSRAN104_xml-2016_08_23-21_33_03__604.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE, skip = 1) 
+6
source share
2 answers

One way to do this is to use two read.csv , the first is the headers, and the second is the data:

 headers = read.csv(file, skip = 1, header = F, nrows = 1, as.is = T) df = read.csv(file, skip = 3, header = F) colnames(df)= headers 

I created the following text file to verify this:

 do not read a,b,c previous line are headers 1,2,3 4,5,6 

Result:

 > df abc 1 1 2 3 2 4 5 6 
+21
source

My perfect solution:

 #' read csv table, wrapper of \code{\link{read.csv}} #' @description read csv table, wrapper of \code{\link{read.csv}} #' @param tolower whether to convert all column names to lower case #' @param skip.rows rows to skip (1 based) before read in, eg 1:3 #' @return returns a data frame #' @export ez.read = function(file, ..., skip.rows=NULL, tolower=FALSE){ if (!is.null(skip.rows)) { tmp = readLines(file) tmp = tmp[-(skip.rows)] tmpFile = tempfile() on.exit(unlink(tmpFile)) writeLines(tmp,tmpFile) file = tmpFile } result = read.csv(file, ...) if (tolower) names(result) = tolower(names(result)) return(result) } 
0
source

All Articles