4

可能重复:
R - 删除 data.frame 中带有 NA 的行

我有一个从以下函数派生的数据框:

complete <- function(directory,id = 1:332) {

   csvfiles <- sprintf("/Users/myname/Desktop/%s/%03d.csv", directory, id)

   nrows <- sapply( csvfiles, function(f) nrow(read.csv(f)))

        rowlabels <- nrow(nrows)

        data.frame(id=sprintf('%3d', id), 
            nobs=sapply(csvfiles,function(x) length(count.fields(x))),
            row.names=rowlabels
           )
       }

此函数计算对象 csvfiles 生成的目录中包含的每个文件的行数。然后它输出一个数据框,显示文件号以及行数(所以两列)

以为我有它,但问题是我现在必须排除每个文件中NA存在实例的行。

我将如何编辑它以忽略每个文件中的那些行,而只计算不NA存在 s 的行?

4

1 回答 1

5

Replace this line:

nrows <- sapply( csvfiles, function(f) nrow(read.csv(f)))

with this line, which uses the complete.cases function:

nrows <- sapply( csvfiles, function(f) nrow(complete.cases(read.csv(f))))

complete.cases takes a data frame and returns a data frame with the same columns, but with all the rows which contain at least one NA thrown out.

于 2013-01-16T23:26:25.817 回答