Determine the number of rows with NAs

2020-04-14 08:34发布

I have a data frame as follows:

     col1   col2    col3
 1    23    17      NA
 2    55    NA      NA
 3    24    12      13
 4    34    23      12

I'm interested in finding the number of rows in col2 and col3 with NAs.

I was surprised that the following code only gave me 4 instead of 2:

numNAs <- rowSums(is.na(all[,2:3]))

Please help.

标签: r dataframe
5条回答
▲ chillily
2楼-- · 2020-04-14 09:07
DF <- read.table(text="     col1   col2    col3
 1    23    17      NA
 2    55    NA      NA
 3    24    12      13
 4    34    23      12", header=TRUE)

This gives the number of rows that contain any NA values in column 2 or 3:

sum(colSums(is.na(DF[,2:3])) > 0)
[1] 2
查看更多
Ridiculous、
3楼-- · 2020-04-14 09:15
test <- read.table(textConnection("     col1   col2    col3
1    23    17      NA
2    55    NA      NA
3    24    12      13
4    34    23      12"))

> table(test$col2,useNA="ifany")

  12   17   23 <NA> 
   1    1    1    1 
> table(test$col3,useNA="ifany")

  12   13 <NA> 
   1    1    2 
查看更多
狗以群分
4楼-- · 2020-04-14 09:19

Another solution adding columns 2 and 3:

> sum(is.na(all[,"col2"] + all[,"col3"]))
[1] 2
查看更多
Ridiculous、
5楼-- · 2020-04-14 09:20

Another solution:

data <- read.table(text='col1   col2    col3
    23    17      NA
    55    NA      NA
    24    12      13
    34    23      12', header=T)

sum(apply(is.na(data[, -1]), 1, any))
查看更多
成全新的幸福
6楼-- · 2020-04-14 09:29

Another short solution:

> sum(!complete.cases(dat[-1]))
[1] 2

where dat is the name of your data frame.

查看更多
登录 后发表回答