How can I embed two CSV files in R?

I have two csv files.

The file contains two columns:

DD1 abct
DD2 geate
DD3 watec
DD4 wwwca21
DD5 bate789

File two has one column:

abct
geate
bate789

I want the truncated file to include those that match file two, i.e.

DD1 abct
DD2 geate
DD5 bate789

Could you let me know how to do this with R?

New for R.

+5
source share
2 answers

First read the files with read.table:

file1 <- read.table("file1.csv", col.names=c("FOO", "BAR"))
file2 <- read.table("file2.csv", col.names=c("BAR"))

Then combine them:

merged <- merge(file1, file2)

And write the result:

write.table(merged, "merged.csv")
+7
source

This is a direct way to do this by doing% in%. This will be the fastest path entirely inside R.

read in files

datf1 <- read.table("file1.csv") #two column file
datf2 <- read.table("file2.csv") #one column file

...% in% , , , ​​FALSE .

datf1 <- datf1[datf1[,2] %in% datf2[,1],]

... 1, 1.

write.table(datf1, "file3.csv", sep = ',', row.names = FALSE, quote = FALSE)
0

All Articles