r 删除不同类型的nas的功能...来自http://stackoverflow.com/questions/4862178/remove-rows-with-nas-in-data-frame

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r 删除不同类型的nas的功能...来自http://stackoverflow.com/questions/4862178/remove-rows-with-nas-in-data-frame相关的知识,希望对你有一定的参考价值。

#' keep rows that have a certain number of NAs anywhere/somewhere and delete others
#' @param df a data frame
#' @param col restrict to the columns where you would like to search for NA; eg, 3, c(3), 2:5, "place", c("place","age")
#' \cr default is NULL, search for all columns
#' @param n integer or vector, 0, c(3,5), number/range of NAs allowed.
#' \cr Range includes both ends 3<=n<=5
#' \cr Range could be -Inf, Inf
#' @return returns a new df with rows that have NA(s) removed
#' @export
z.na.keep = function(df, col=NULL, n=0){
    if (!is.null(col)) {
        df.temp = df[,col]
    } else {
        df.temp = df
    }

    if (length(n)==1){
        if (n==0) {
            # simply call complete.cases which might be faster
            result = df[complete.cases(df.temp),]
        } else {
            # credit: http://stackoverflow.com/a/30461945/2292993
            log <- apply(df.temp, 2, is.na)
            logindex <- apply(log, 1, function(x) sum(x) == n)
            result = df[logindex, ]
        }
    }

    if (length(n)==2){
        min = n[1]; max = n[2]
        log <- apply(df.temp, 2, is.na)
        logindex <- apply(log, 1, function(x) {sum(x) >= min && sum(x) <= max})
        result = df[logindex, ]
    }

    return(result)
}

以上是关于r 删除不同类型的nas的功能...来自http://stackoverflow.com/questions/4862178/remove-rows-with-nas-in-data-frame的主要内容,如果未能解决你的问题,请参考以下文章

R:在扩展后使用summarise_all(funs(sum))返回0,即使删除了NAs

通过 http 从连接到服务器的 NAS 下载文件

使用等待和异步返回字符串列表

R语言中不同类型的聚类方法比较

R中NA的条件操作

r 移动列的功能来自http://stackoverflow.com/questions/18339370/reordering-columns-in-a-large-dataframe