Reputation: 4555
Sorry for the seemingly easy question, but I have been searching and am unable to find a solution.
Basically I have a csv file that looks like this:
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
How can I get it into a data frame that would look like this?
ax ay az bx by bz
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
Upvotes: 1
Views: 98
Reputation: 193507
I would just use read.csv
twice. This will also make it so that your numeric columns are actually numeric, unlike @alexwhan's answer:
## 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
Upvotes: 1
Reputation: 16026
Here's one option, but it seems like there should be a nicer way to do it:
dat <- read.csv(textConnection("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"), head = F, stringsAsFactors = F)
names(dat) <- paste0(dat[1,], dat[2,])
dat <- dat[-c(1:2),]
dat
# ax ay az bx by bz
# 3 10 1 5 22 1 6
# 4 12 2 6 21 3 5
# 5 12 2 7 11 3 7
# 6 13 1 4 33 2 8
# 7 12 2 5 44 1 9
Upvotes: 0