Reading two-line headers in R

前端 未结 5 748
梦如初夏
梦如初夏 2020-11-29 05:22

What is the best way to read a file into R when the header has two necessary lines for the header?

This happens to me all the time, as people often use one line for

5条回答
  •  無奈伤痛
    2020-11-29 06:00

    Here is a function to read in headers over multiple lines, largely based on Gavin Simpson's excellent answer.

    The function defaults to comma separated values and two lines of header, and returns a data.frame with the first line in the file as header.

    The function:

    read.multi.line.header <- function(path, header.lines = 2, sep = ","){
    
      header <- scan(path, nlines = 1, what = character(), sep = sep)
    
      data <- read.table(path, skip = header.lines, header = FALSE, sep = sep)
    
      base::names(data) <- header
    
      return(data)
    }
    

    Produces:

    mydata <- read.multi.line.header(path = "data.txt")
    
    > head(mydata)
          trt      biomass      yield
    1      C2        17.76     205.92
    2      C2        17.96     207.86
    3      CC        17.72     197.22
    4      CC        18.42     205.20
    5     CCW        18.15     200.51
    6     CCW        17.45     190.59
    

提交回复
热议问题