2017-01-25 96 views
-2

我有兩個數據幀:如何比較兩列

DF1

V1    V2 
ec:2.7.11.1  hsa:9344 
ec:2.7.11.1  hsa:5894 
ec:2.7.11.1  hsa:673 
ec:2.7.12.2  hsa:5607 
ec:2.7.11.24 hsa:5598 
ec:2.7.11.25 hsa:9020 
ec:2.7.11.24 hsa:51701 
ec:2.3.1.250 hsa:64840 

DF2

V1    
9344 
5607 
9020 
64840 

我想:

V1    V2 
ec:2.7.11.1  hsa:9344 
ec:2.7.12.2  hsa:5607 
ec:2.7.11.25 hsa:9020 
ec:2.3.1.250 hsa:64840 

回答

0

你可以這樣做:
數據:

df=read.table(text=" V1    V2 
ec:2.7.11.1  hsa:9344 
       ec:2.7.11.1  hsa:5894 
       ec:2.7.11.1  hsa:673 
       ec:2.7.12.2  hsa:5607 
       ec:2.7.11.24 hsa:5598 
       ec:2.7.11.25 hsa:9020 
       ec:2.7.11.24 hsa:51701 
       ec:2.3.1.250 hsa:64840",h=T) 
df2=read.table(text="V1    
9344 
5607 
9020 
64840",h=T) 

然後在比較過程中使用sub()刪除非數字符號。

df[sub("\\D*","",df$V2) %in% df2$V1,] 
       V1  V2 
    1 ec:2.7.11.1 hsa:9344 
    4 ec:2.7.12.2 hsa:5607 
    6 ec:2.7.11.25 hsa:9020 
    8 ec:2.3.1.250 hsa:64840 
0

下面是使用paste0()df2$V1

df <- read.table(header=TRUE, text= 
" V1    V2 
ec:2.7.11.1  hsa:9344 
ec:2.7.11.1  hsa:5894 
ec:2.7.11.1  hsa:673 
ec:2.7.12.2  hsa:5607 
ec:2.7.11.24 hsa:5598 
ec:2.7.11.25 hsa:9020 
ec:2.7.11.24 hsa:51701 
ec:2.3.1.250 hsa:64840") 
df2 <- read.table(header=TRUE, text= 
"V1    
9344 
5607 
9020 
64840") 
df3 <- data.frame(V2=paste0("hsa:", df2$V1)) 
merge(df, df3) 

或在一行中的溶液:

merge(df, data.frame(V2=paste0("hsa:", df2$V1)))