使用R为多个列定义一个名称

时间:2013-07-25 08:42:55

标签: r

我有这个:data1

       Aux     Cux
aa     3       3 
bbb    0       0
ccc    7.8     7.8
dddd   2.32    2.09
eee    5.68    5.45

和此,data2

       Aux     Cux
aa     6       6
bbb    0.3     0.4
ccc    7.5     2.9
dddd   2.09    1.48
eee    0.62    0.62

我想要这个最终数据

          file1     |     file2      |
       Aux  |  Cux  |  Aux  |  Cux   |
aa     3    |  3    |  6    |  6     |
bbb    0    |  0    |  0.3  |  0.4   |
ccc    7.8  |  7.8  |  7.5  |  2.9   |
dddd   2.32 |  2.09 |  2.09 |  1.48  |
eee    5.68 |  5.45 |  0.62 |  0.62  |

我认为,csv文件会像这样保存

,file1,,file2,,
,Aux,Cux,Aux,Cux
aa,3,3,6,6
bbb,0,0,0.3,0.4
ccc,7.8,7.8,7.5,2.9
dddd,2.32,2.09,2.09,1.48
eee,5.68,5.45,0.62,0.62

我该怎么办?谢谢

2 个答案:

答案 0 :(得分:2)

数据框:

data1 <- read.table(text = "Aux     Cux
aa     3       3 
bbb    0       0
ccc    7.8     7.8
dddd   2.32    2.09
eee    5.68    5.45", header = TRUE, row.names = 1)

data2 <- read.table(text = "Aux     Cux
aa     6       6
bbb    0.3     0.4
ccc    7.5     2.9
dddd   2.09    1.48
eee    0.62    0.62", header = TRUE, row.names = 1)

创建一个字符矩阵:

dat <- as.matrix(rbind(c(names(data1), names(data2)),
                       cbind(data1, data2)))

设置行名和列名:

dimnames(dat) <- list(c("", rownames(data1)), c("file1", "", "file2", ""))

写下表格:

write.csv(dat, file = "filename.csv", quote = FALSE)

生成的文件:

,file1,,file2,
,Aux,Cux,Aux,Cux
aa,3,3,6,6
bbb,0,0,0.3,0.4
ccc,7.8,7.8,7.5,2.9
dddd,2.32,2.09,2.09,1.48
eee,5.68,5.45,0.62,0.62

答案 1 :(得分:0)

试试这个:

data3 = cbind(data1, data2)
header = matrix(c('file1','','file2',''), nrow=1)
write.table(header, "output.csv", sep=',', quote=F, col.names=F, row.names=F)
write.table(data3, "output.csv", append = T, row.names=F)

你可能只需要使用row.names来实现这一点。