-2

I have two text files File 1

File1=read.table("C:\\file1.txt", sep="")
Value   name
  0.2    sam
  0.4  david
  3    david
  7    nicola

File 2

File2=read.table("C:\\file2.txt", sep="")
Value   name
  0.8 nicola
  0.9  david

Keep only rows where names exist in both files. For instance, desired outputs:

File 1

Value   name
  7  nicola

File 2

Value   name
  0.8  nicola

Note that Dived was removed in my desired output because I have 2 David in file 1 and 1 David in File 2. sam was removed because we do not have it in file2

temor
  • 935
  • 2
  • 10
  • 26
  • I know that your code is only an example; nevertheless: **never** use absolute paths in your scripts. The resulting code is completely unportable, and this is actually a huge problem in real-word code. – Konrad Rudolph Dec 07 '15 at 10:40
  • 2
    You could get both values simultaneously by a simple merge such as `merge(File1, File2, by = "name")` – David Arenburg Dec 07 '15 at 11:01

1 Answers1

2

We can use %in%

df1[df1$name %in% df2$name,]
#  Value  name
#2   0.4 david
df2[df2$name %in% df1$name,]
#  Value  name
#2   0.9 david
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @temor Then, you should have showed that in the example. We can't guess what is in your original file. – akrun Dec 07 '15 at 18:05
  • @temor Based on the new update, the question doesn't seem to be duplicate. But, as it is already tagged as dupe, can you post this as a new question. – akrun Dec 08 '15 at 03:01
  • @temor I answered the question you posted. So, I don't have to remove the answer. If it is not the question you have, you should post a new question. – akrun Dec 08 '15 at 06:41