I need to amend the dataframe "DF1" by matching its 1st (and only) column with 2nd column of "DF2" and printing the matched column by preserving the order of rownames in DF1. I also need to replace the non-matching rows with 0. These are two examples of the data frames I have:
"DF1"
Ccd
Kkl
Sop
Mnn
Msg
Xxy
Zxz
Ccd
Msg
"DF2"
3 Ab
5 Abc
5 Ccd
9 Kkl
5 Msg
13 Sop
19 Klj
Code
read.table("a.txt")->DF1
read.table("b.txt")->DF2
colnames(DF1)<-c("b")
colnames(DF2)<-c("a", "b")
DF3 <- merge(DF1,DF2, by="b", all.x=TRUE) #
DF3$a[is.na(DF3$a)] <- 0 #substitute NA with 0
Output I get from above code is:
b a
Ccd 5
Ccd 5
Kkl 9
Mnn 0
Msg 5
Msg 5
Sop 13
Xxy 0
Zxz 0
Output I actually need is:
Ccd 5
Kkl 9
Sop 13
Mnn 0
Msg 5
Xxy 0
Zxz 0
Ccd 5
Msg 5