0

I have a dataframe df

A    B
x    y
x    NA
NA   NA

I want to create a new column, say df$C, that has value 0 if that row only contains NA and 1 otherwise. My desire df is

A    B    C
x    y    1
x    NA   1
NA   NA   0

Really appreciate any help

Sotos
  • 51,121
  • 6
  • 32
  • 66
TDo
  • 686
  • 4
  • 9
  • 22
  • 1
    quick and dirty: `df$C = rowSums(is.na(df)) == 0` – MichaelChirico Apr 08 '17 at 18:40
  • @MichaelChirico It does not work, it returns 1, 0, 0 instead of 1, 1, 0 – TDo Apr 08 '17 at 19:12
  • This is why you need to [provide a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). The code works if `df[2, 'B']` is _actually_ `NA`, which it appears it is not. – MichaelChirico Apr 08 '17 at 19:13
  • To get 1, 1, 0, surely just tweak @MichaelChirico 's answer to `df$C = as.numeric(rowSums(is.na(df)) != 2)` (where 2 is the number of columns in `df`, excluding C). So you get 0 if all the entries in a row are `NA`, and 1 otherwise. – hodgenovice Apr 08 '17 at 19:21
  • and a bit more generic: `df$C <- as.integer(rowSums(is.na(df)) != ncol(df))` – Jaap Apr 08 '17 at 19:31

0 Answers0