#' Returns the locations of the elements of the first argument whose
#' values are equal to one of the elements in the second argument
#'
#' @param a vector
#' @param b vector
#' @param keep = 1 not to sort the result
#'
#' @return vector consisting of the locations of the elements of
#' the first argument whose
#' values are equal to one of the elements in the second argument, or 0
#'
#' @details
#' \code{loceq( a, b, keep=0 )} is equivalent to \cr
#' \code{which( match(a,b, nomatch=0) > 0 ) } \cr
#' or \cr
#' \code{which( a \%in\% b )} .\cr
#'
#' loceq(letters, c("x","cc","a"))  returns c(24,1) \cr
#' With keep=0, the result will be sorted according to the order
#' of appearance in the first argument.\cr
#' loceq(letters, c("x","cc","a"), 0)  returns c(1,24) \cr\cr
#'  If subset below contains a subset of the variable names of
#'  a data frame,\cr
#'  loc=loceq( colnames(dataframe), subset ) \cr
#'  wii return the location of those variables.\cr\cr
#'  It will return 0 if no match.
#'
#' @examples
#' loceq(letters, c("x","cc","a"))
#' loceq(letters, c("x","cc","a"), 0)
#' loceq(c("x","cc","a"), letters)
#' loceq(c("x","cc","a"), letters, 0)
#'
#' @export
#'

loceq <- function( a, b, keep=1 ){
 # returns the locations of the elements of a whose
 # values are equal to one of the elements in b
 # Shin-ichi Mayekawa
 # 121018
 # keep: 20140528
 # comments added: 20140708,20150131
 # new algorithm and -1 -> 0: 20150530
 # roxgen comments: 20161124

 #
 # This function returns a vector of the locations of the elements of a whose
 # values are equal to one of the elements in b.
 #
 # For example,
 #   loceq(letters, c("a","cc","x"), 0)  returns c(1,24)
 # and
 #   loceq(c("a","cc","x"), letters, 0)   returns c(1,3)
 #
 # When keep = 1, a[loceq(a,b)] has the same order as b.
 #   loceq(letters, c("x","cc","a"))  returns c(24,1)
 # but
 #   loceq(letters, c("x","cc","a"), 0)  returns c(1,24)
 # and
 #   loceq(c("x","cc","a"), letters)   returns c(3,1)
 # but
 #   loceq(c("x","cc","a"), letters, 0)   returns c(1,3)
 #
 #
 # When there are no match, 0 will be returned.
 #
 #  In order to find the locations of the subset of the variables
 # in a dataframe, use
 #   loc=loceq( colnames(dataframe), subset )
 #
 # For example,
 #  cn=c("x1","y1","gender","a","b")
 #  loceq(cn,c("a","x1"))  returns c(4,1)
 #  loceq(cn,c("x1","a"))  returns c(1,4)
 #

 # native match function
 matchres=match(a,b, nomatch=0) # this contains the original location in b
 loc=which(matchres > 0)
 if( length(loc) == 0 ) loc=0
 if( keep != 1  |  length(loc) == 1 ) return( loc )

 # sort the result according to match result
 matchres=matchres[matchres > 0]
 od=order(matchres)
 loc=loc[od]

 return( loc )

} # end of loceq





