-2

I have a large data frame that contains 900 variables per row. I am trying to write a function that gives me the name of each column that contains a NA for each row.

For example:

x-> 

               mpg  cyl disp hp draw wt
Mazda RX4     21.0   6  160 110 NA   2.62
Mazda RX4 Wag 21.0   6  NA  110 3.90 NA 
Datsun 710    22.8   4  NA  93  NA   NA 

I would like a function to return:

Mazda RX4:   "draw"
Mazda RX4 Wag: "disp", "wt"
Datsun 710: "disp","draw","wt"

1 Answer 1

1

Run apply by row to select from colnames(x). Probably going to get a list since the result is ragged.

 apply(x, 1, function(x2) colnames(x)[ is.na(x2) ] )
$`Mazda RX4`
[1] "draw"

$`Mazda RX4 Wag`
[1] "disp" "wt"  

$`Datsun 710`
[1] "disp" "draw" "wt"  
2
  • Wow thanks a lot! I'm new with R and really appreciate the help. My only question is what will x2 be defined as? Apr 20, 2016 at 15:04
  • 1
    x2 is a temporary value that will change as apply moves from row to row, and after the function is done, then x2 will be available to be garbage collected. Technically in the terms that describe R's syntax it is is a formal argument to an anonymous function.
    – IRTFM
    Apr 20, 2016 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.