我只会用read.csv
两次。这也将使您的数字列实际上是数字,与@alexwhan 的回答不同:
## Create a sample csv file to work with
cat("a,a,a,b,b,b", "x,y,z,x,y,z", "10,1,5,22,1,6", "12,2,6,21,3,5",
"12,2,7,11,3,7", "13,1,4,33,2,8", "12,2,5,44,1,9",
file = "test.csv", sep = "\n")
## Read in the data first, and the headers second
x1 <- read.csv(file = "test.csv", header = FALSE, skip = 2)
x2 <- read.csv(file = "test.csv", header = FALSE, nrows = 2)
## Collapse the second object into a single vector
names(x1) <- apply(x2, 2, paste, collapse = "")
x1
# ax ay az bx by bz
# 1 10 1 5 22 1 6
# 2 12 2 6 21 3 5
# 3 12 2 7 11 3 7
# 4 13 1 4 33 2 8
# 5 12 2 5 44 1 9
## As can be seen, the structure is also appropriate
str(x1)
# 'data.frame': 5 obs. of 6 variables:
# $ ax: int 10 12 12 13 12
# $ ay: int 1 2 2 1 2
# $ az: int 5 6 7 4 5
# $ bx: int 22 21 11 33 44
# $ by: int 1 3 3 2 1
# $ bz: int 6 5 7 8 9