2017-05-22 3 views
0

Guten Tag
1) Gibt es eine R-Funktion ähnlich Excel Match-Funktion?R-Funktion ähnlich Excel Match?

2) Ich habe mein eigenes gemacht wie unten (lange .. TT)
Könnte jemand vorschlagen, dass Dinge verbessert werden müssen? Oder anders?

fmatch2<-function(ss1, ss2) { #ss1 correspond the first argument of Excel match function. ss2 for the second. 
fmatch<-function(ii,ss) { # return location in ss where ii match. 
    if (length(which(ss==ii))>0) { 
     rr<- min(which(ss==ii)) 
    } else { 
     if (length(which(ss>ii))>0) 
     {rr<-min(which(ss>ii))-1 } 
    } 
return(rr) 
}  
rr<-list() 
n<-1 
for (x in ss1) { # apply fmatch to each member in ss1 
    nn<-fmatch(x,ss2[1:n]) 
    rr<-rbind(rr,nn) 
    n<-n+1 
} 
as.vector(unlist(rr[,1])) 
} 

Verwendungen der Funktion fmatch2 wie folgt.
Excel nachahmen "= MATCH (H1, $ I $ 1: 1,1)". Der Elementname der Liste unter "ch, ci" entspricht der Spalte H, Spalte I. Das Ergebnis ist die Liste cn.

x<-data.frame(cf=c(0,1,2,3,4,5),ch=c(0,0,3,6,6,6),ci=c(0,0,3,7,11,13)) 

y<-data.frame(cf=c(0,1,2,3,4,5),ch=c(0,0,3,6,6,6),ci=c(0,0,3,7,11,13),cn=fmatch2(x[[2]],x[[3]])) 
+0

tut 'helfen match'? Es gibt nur das erste Spiel zurück. Sonst, '? Grep' –

+0

Suchst du den Übereinstimmungsindex (d. H. Welche Zeile hat Übereinstimmungen)? – akash87

+1

Lesen Sie das Dokument des Excel 'match' (https://support.office.com/en-us/article/MATCH-function-e8dffd45-c762-47d6-bf89-533f4a37673a), es scheint, dass es tatsächlich zwei entspricht Funktionen in R: es ist 'match', wenn' match_type' 0 ist und 'findInterval' mit dem Standardwert. OP, schau dir 'findInterval' an. – nicola

Antwort

0

Ofcourse ich bin nicht ganz sicher, was Sie zu tun versuchen, wie ich Ihre fmatch2 Funktion NA für ch==6 zurückzukehren erwarten würde (da 6 nicht in ci), aber ich lieben Dinge zu tun, mit dplyr:

library(dplyr) 
result <- x %>% # "%>%" means "and then" 
      mutate(chInCi = match(ch, x$ci)) #adds a column named "chInCi" with the position in ci of the first match of the value in ch 

Ergebnis

cf ch ci chInCi 
1 0 0 0  1 
2 1 0 0  1 
3 2 3 3  3 
4 3 6 7  NA 
5 4 6 11  NA 
6 5 6 13  NA 
Verwandte Themen