Reading two-line headers in R

前端 未结 5 762
梦如初夏
梦如初夏 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 05:45

    A slightly different explained step by step approach:

    1. Read only the first two lines of the files as data (without headers):

      headers <- read.table("data.txt", nrows=2, header=FALSE)
      
    2. Create the headers names with the two (or more) first rows, sappy allows to make operations over the columns (in this case paste) - read more about sapply here :

      headers_names <- sapply(headers,paste,collapse="_")
      
    3. Read the data of the files (skipping the first 2 rows):

      data <- read.csv(file="data.txt", skip = 2, header=FALSE)
      
    4. And assign the headers of step two to the data:

      names(data) <- headers_names
      

    The advantage is that you would have clear control of the the parameters of read.table (such as sep for commas, and stringAsFactors - for both the headers and the data)

提交回复
热议问题