Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip specific rows using read.csv in R [duplicate]

Tags:

r

read.csv

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

In the original file my headers are on line 2.

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

Can anyone suggest how to skip multiple specific rows in R, below is what I was able to cobble together?

Can I pass a vector to the skip argument specifying the exact rows 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) 
like image 952
TheGoat Avatar asked Aug 23 '16 21:08

TheGoat


People also ask

How do you skip columns in R?

The most easiest way to drop columns is by using subset() function. In the code below, we are telling R to drop variables x and z. The '-' sign indicates dropping variables. Make sure the variable names would NOT be specified in quotes when using subset() function.

What does header true mean in R?

• The header = TRUE argument tells R that the first row of your. file contains the variable names.


2 Answers

One way to do this is using two read.csv commands, the first one reads the headers and the second one 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've created the following text file to test this:

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

The result is:

> df   a b c 1 1 2 3 2 4 5 6 
like image 184
R. Schifini Avatar answered Oct 08 '22 14:10

R. Schifini


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) } 
like image 44
Jerry T Avatar answered Oct 08 '22 13:10

Jerry T