Reading two-line headers in R

前端 未结 5 752
梦如初夏
梦如初夏 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:40

    Almost the same method to the other answers, just shortening to 2 statements:

    dat <- "trt   biomass    yield
    crop    Mg/ha    bu/ac
    C2      17.76   205.92
    C2      17.96   207.86
    CC      17.72   197.22
    CC      18.42   205.20
    CCW     18.15   200.51
    CCW     17.45   190.59
    P       3.09    0.00
    P       3.34    0.00
    S2      5.13    49.68
    S2      5.36    49.72"
    
    header <- sapply(read.table(text=dat, nrow=2), paste, collapse="_")
    result <- read.table(text=dat, skip=2, col.names=header)
    

    Result:

    > head(result,2)
      trt_crop biomass_Mg/ha yield_bu/ac
    1       C2         17.76      205.92
    2       C2         17.96      207.86
    ...
    

提交回复
热议问题