使用readLines
with 2 作为限制,将它们解析paste0
在一起,然后使用read.table
with skip =2
and header=FALSE
(默认值)读入。通过分配列名完成该过程:
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
"
您可能会使用文件参数,但使用text
read-functions 的参数会使它更加独立:
readLines(textConnection(dat),n=2)
#[1] "trt\tbiomass\tyield" "crop\tMg/ha\tbu/ac"
head2 <- read.table(text=readLines(textConnection(dat),n=2), sep="\t", stringsAsFactors=FALSE)
with(head2, paste0(head2[1,],head2[2,]) )
# [1] "trtcrop" "biomassMg/ha" "yieldbu/ac"
joinheadrs <- with(head2, paste0(head2[1,],head2[2,]) )
newdat <- read.table(text=dat, sep="\t",skip=2)
colnames(newdat)<- joinheadrs
#-------------------
> newdat
trtcrop biomassMg/ha yieldbu/ac
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
7 P 3.09 0.00
8 P 3.34 0.00
9 S2 5.13 49.68
10 S2 5.36 49.72
使用带有下划线分隔符的粘贴可能会更好:
joinheadrs <- with(head2, paste(head2[1,],head2[2,] ,sep="_") )
joinheadrs
#[1] "trt_crop" "biomass_Mg/ha" "yield_bu/ac"