1

很抱歉这个看似简单的问题,但我一直在寻找,但无法找到解决方案。

基本上我有一个 csv 文件,如下所示:

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

如何将它放入看起来像这样的数据框中?

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
4

2 回答 2

1

我只会用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
于 2013-09-26T09:47:30.200 回答
0

这是一个选项,但似乎应该有更好的方法来做到这一点:

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
于 2013-09-26T06:03:03.973 回答