0

I need a function in R which is doing the following. I have a matrix with some data

mydata <- data.frame (matrix(c(1,2,3,NA,2,3,NA,NA,2), 3,3))

mydata
  X1 X2 X3
1  1 NA NA
2  2  2 NA
3  3  3  2

No I want to check every column of this matrix if there is any NA in a column and create a vector which stores 0 if there is a NA in a column or 1 if there is no NA in the column.

So check column X1: if NA is in this column write 0 to the vector, if not write 1 to the vector. Then check the next column and so on.

After checking mydata the vector should look like this

(1 0 0)

with

colnames(mydata)[colSums(is.na(mydata)) > 0]

I get the column names which have NA. But how can I use this function to create the vector?

user2348157
  • 103
  • 3
  • 11

1 Answers1

0

We can coerce the logical vector from colSums on the logical matrix to binary with as.integer

as.integer(!colSums(is.na(mydata)))
#[1] 1 0 0
akrun
  • 874,273
  • 37
  • 540
  • 662