R功能类似于Excel的匹配?

时间:2017-05-22 15:09:10

标签: r match

美好的一天
1)是否存在类似于Excel匹配函数的R函数?

2)我已经自己制作了如下(longy..TT)
  任何人都可以提出需要改进的事情吗?或者其他方式?

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])) 
}

函数fmatch2的用法如下。
模仿Excel&#34; = MATCH(H1,$ I $ 1:1,1)&#34;。下面列表的元素名称&#34; ch,ci&#34;对应于列H,列I.结果是名为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]]))

1 个答案:

答案 0 :(得分:0)

当然,我并不完全确定你要做什么,因为我希望你的fmatch2函数返回NA ch==6(因为6是不存在于ci),但我喜欢用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

结果

 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