简体   繁体   English

使用R组合多个data.frame

[英]Combining multiple data.frames using R

I have several txt files in which each txt file contains 3 columns(A,B,C). 我有几个txt文件,其中每个txt文件都包含3列(A,B,C)。 Column A will be common to all txt files. 列A将对所有txt文件通用。 Now I want to combine txt files with coulmn A appearing only once while the other columns (B and C) of respective files. 现在,我想将txt文件与仅出现一次的column A合并,而将各个文件的其他列(B和C)合并。 I used cbind but it creates a data frame with repeats of column A, which I dont want. 我使用了cbind但是它创建了重复的A列的数据帧,这是我不想要的。 The column A must be repeated only once. A列只能重复一次。 Here is the R code I tried: 这是我尝试过的R代码:

data <- read.delim(file.choose(),header=T)   
data2 <- read.delim(file.choose(),header=T)
data3 <- cbind(data1,data2)
write.table(data3,file="sample.txt",sep="\t",col.names=NA)

Unless your files are all sorted precisely the same, you'll need to use merge : 除非文件的排序完全相同,否则需要使用merge

dat <- merge(data,data2,by="A")
dat <- merge(dat,data3,by="A")

This should automatically prevent you from having multiple A's, since merge knows they're all a key/index column. 这将自动防止您拥有多个A,因为合并知道它们都是键/索引列。 You'll likely want to rename the duplicate B's and C's before merging. 您可能需要在合并之前重命名重复的B和C。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM