Chris
Chris

Reputation: 1353

Reading CSV using R where header is on the second line

I know that in R I can read in a csv file using read.csv. I also know that by setting header = TRUE I can indicate to R that there is a header with variable names on the first row.

However, I am trying to read in a csv that places a timestamp on the first row and the header / variable names on the second. I can obviously manually strip off the first line before loading it into R, but it’s a pain to do this each time. Is there an elegant solution to this in R?

Upvotes: 3

Views: 12162

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

For the subjective "elegant", you may want to look at fread from "data.table" which generally does a good job of figuring out where the data actually start.

An example:

Create a fake CSV file in our workspace

The first line has "something" and the actual data starts on the second line with the headers "V1", "V2", and "V3".

x <- tempfile()
cat("something",
    "V1,V2,V3",
    "1,2,3", "4,5,6", "7,8,9", sep = "\n", file = x)

Load "data.table" and try fread

Seems to work out of the box! Obviously replace x with the name of your actual CSV file.

library(data.table)
fread(x)
#    V1 V2 V3
# 1:  1  2  3
# 2:  4  5  6
# 3:  7  8  9

Upvotes: 3

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

Use the skip argument to read.csv

read.csv(.... , skip=1)

Upvotes: 11

Related Questions