Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data table in R: Counting NA values in columns by using column index

Tags:

r

data.table

I have data.table G with columns A, B, C:

code below counts NA values in the column A:

G[is.na(A), .N]

But when I try to use Column index(For column A index = 1) - I see no result:

G[is.na(.SD), .N, .SDcols = 1]

How can I fix this problem correctly?

like image 566
evgenii ershenko Avatar asked Sep 01 '25 01:09

evgenii ershenko


1 Answers

We can get the count from the 'j' itself.

G[, sum(is.na(.SD)),  .SDcols = 1]

and if there are multiple columns, loop through the columns and get the sum of NA elements

G[, lapply(.SD, function(x) sum(is.na(x))), .SDcols = 1:2]
like image 130
akrun Avatar answered Sep 04 '25 04:09

akrun