在R中创建“min”函数

时间:2017-11-09 20:02:14

标签: r function

我的一位朋友最近拍了一个中期,其中第一个问题要求他在R中创建自己的“baby.min()”函数而不使用“sort()”或“min()”。该功能的操作方式与“min()”相同。也就是说,min(x)返回某个向量x中的最小值。

我对编程很新,因此提出了一个看似过于复杂的解决方案;但是,我想知道这个功能是多么简洁。

作为参考,我对该功能的想法如下:

baby.min <- function(x){
  if (length(x) == 0) {
    return(Inf)
  } else {
    counter <- 0
    for (i in 1:length(x)){
      for (j in 1:length(x) & j != i){
        if (x[i] <= x[j]) {
          counter <- counter + 1
        } else {
          break
          counter <- 0
        }
      }
    if (counter == length(x) - 1){
      return(x[i])
    }
    }
  }
}

(同样,我知道这可能是一个糟糕的解决方案;我只是想看到比我自己更好的程序员可以解决它的不同方式。)

3 个答案:

答案 0 :(得分:3)

      String oauthHost = InetAddress.getByName(OAUTH_HOST).getHostAddress();
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

        // Basic Auth
        String plainCreds = clientId + ":" + clientSecret;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = org.apache.commons.net.util.Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);
        headers.add("Authorization", "Basic " + base64Creds);
        // params
        map.add("username", username);
        map.add("password", password);
        map.add("grant_type", GRANT_TYPE);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
                headers);
        // CALLING TOKEN URL
        OauthTokenRespone res = null;
        try {
            res = restTemplate.postForObject(OAUTH_TOKEN_URL.replace(OAUTH_HOST, oauthHost), request,
                    OauthTokenRespone.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

仅适用于@bouncyball, @JsonIgnoreProperties(ignoreUnknown = true) public class OauthTokenRespone { private String access_token; private String token_type; private String refresh_token; private String expires_in; private String scope; private String organization; //getter and setter } 选项:

baby.min <- function(x) {
  my_min = Inf
  for (i in seq_along(x)) {
    if (x[i] < my_min) my_min = x[i]
  }
  return(my_min)
}

baby.min(1:10)
# [1] 1

baby.min(integer(0))
# [1] Inf

x = rnorm(100)
identical(min(x), baby.min(x))
# [1] TRUE

但是,如果你想绕过“不要使用na.rmbaby.min <- function(x, na.rm = FALSE) { if (na.rm) { x = na.omit(x) } else { if (anyNA(x)) return(NA) } my_min = Inf for (i in seq_along(x)) { if (x[i] < my_min) my_min = x[i] } return(my_min) } ”,但得到一点点聪明,你可以这样做;)

sort()

答案 1 :(得分:1)

R中的解决方案完全,如min():

BabyMin <- function(vector){    
  min <- Inf    
  if (length(vector)==0){
    # write(paste0("Warning message:\n",    
    #              "no non-missing arguments to min; returning Inf"), stderr())
    warning("no non-missing arguments to min; returning Inf", call.=F)    
  } else if (any(is.na(vector))){ 
    return(NA)    
  } else {    
    for (n in 1:length(vector)){    
      value <- vector[n]    
      if (value < min){    
        min <- value    
      }    
    }     
  }    
  return(min)    
}    

a <- c(4,2,3,1,7,8,9,12)    
BabyMin(a)    
# [1] 1    

b <- NULL    
BabyMin(b)    
# Warning message:    
# no non-missing arguments to min; returning Inf    
# [1] Inf    

c <- c(NA, rnorm(2))    
BabyMin(c)    
# [1] NA    

答案 2 :(得分:0)

我不知道select tf.idFile from tagfile tf join tag t on tf.idtag = t.id group by tf.idFile having sum(case when t.value in ('a', 'b', 'c') then 1 else 0 end) = 3 and count(*) = 3; -- length of list ,但这是我计划这个功能的方法。

r

作为一种优秀的编程习惯,总是从函数中返回一些东西,无论是结果还是错误(或错误代码)。