Is it possible to set na.rm to TRUE globally?

前端 未结 4 1295
情歌与酒
情歌与酒 2020-12-05 13:56

For commands like max the option na.rm is set by default to FALSE. I understand why this is a good idea in general, but I\'d like to t

4条回答
  •  生来不讨喜
    2020-12-05 14:55

    There were several answers about changing na.rm argument globally already. I just want to notice about partial() function from purrr or pryr packages. Using this function you can create a copy of existing function with predefined arguments:

    library(purrr)
    .mean <- partial(mean, na.rm = TRUE)
    
    # Create sample vector
    df <- c(1, 2, 3, 4, NA, 6, 7)
    
    mean(df)
    >[1] NA
    
    .mean(df)
    >[1] 3.833333
    

    We can combine this tip with @agstudy answer and create copies of all functions with na.rm = TRUE argument:

    library(purrr)
    
    # Create a vector of function names https://stackoverflow.com/a/17423072/9300556
    Funs <- Filter(is.function,sapply(ls(baseenv()),get,baseenv()))
    na.rm.f <- names(Filter(function(x) any(names(formals(args(x)))%in% 'na.rm'),Funs))
    
    # Create strings. Dot "." is optional
    fs <- lapply(na.rm.f,
                 function(x) paste0(".", x, "=partial(", x ,", na.rm = T)"))
    
    eval(parse(text = fs)) 
    

    So now, there are .all, .min, .max, etc. in our .GlobalEnv. You can run them:

    .min(df)
    > [1] 1
    .max(df)
    > [1] 7
    .all(df)
    > [1] TRUE
    

    To overwrite functions, just remove dot "." from lapply call. Inspired by this blogpost

提交回复
热议问题