将2个csv头合并为R中的1

时间:2013-09-26 05:55:25

标签: r dataframe

对于看似简单的问题感到抱歉,但我一直在搜索,但无法找到解决方案。

基本上我有一个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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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