how to remove rows with all NULL values in R

Viewed 295

I have the following matrix:

id A    B    C
1  1    2    5
2  4    6    7
3  NULL NULL NULL
4  NULL 4    6

I will like to remove just the row with id 3. Note that when I use unique() it is still kept because id is unique per se.

1 Answers

It is possible that the columns are list because NULL would not exist in a vector. If that is the case

i1 <- Reduce(`&`, lapply(df1[-1], function(x) sapply(x, is.null)))
df1[!i1,]
#   id A B C
#1  1 1 2 5
#2  2 4 6 7
#4  4   4 6

If the NULL is a character "NULL", an option is

i1 <- rowSums(df1[-1] == "NULL") == ncol(df1[-1])
df1[!i1,]

data

df1 <- data.frame(id = 1:4, A = I(list(1, 4, NULL, NULL)),
     B = I(list(2, 6, NULL, 4)), C = I(list(5, 7, NULL, 6)))
Related