user11538509
user11538509

Reputation:

Handling NULL after if() inside appply

I have a situation where apply returns a list with many NULL entries. The code I use is quite long, so I reproduce the problem with a simple example.

# Generate data.
df <- data.frame(a= c(1,2, NA, 6),
                 b= c(1, 7, 3, 7))

# Return only columns that have NAs.
my_list <- apply(df, 2, function(col_i){
  if(any(is.na(col_i))){
    return(col_i)
  }})

Running this gives us

my_list
$a
[1]  1  2 NA  6

$b
NULL

My problem is that I get many Null entries so that I can not work with the results. How can I (a) avoid apply to return the NULL entries or (b) discard all NULL entries in my_list?

So the expected output is

my_list
$a
[1]  1  2 NA  6

Again, the actual code I use is more complex than that. So please do not suggest using something like df[ , !complete.cases(t(df)), drop= FALSE] which also returns columns that contain any missings. My question is not about how to get columns with any missings but how to handle NULLentries in apply. I want to keep the if part inside apply.

Upvotes: 0

Views: 34

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Every function has to return something so you can't really avoid returning something but you can remove them :

Filter(length, apply(df, 2, function(col_i) if(any(is.na(col_i))) return(col_i)))

#$a
#[1]  1  2 NA  6

Upvotes: 1

Related Questions