Reputation: 901
I have a data frame name df on R:
a b c d
1 BR073ELAC5EIANID-115781 2014-04-14 7 3
2 BR073ELAC5EIANID-115781 2014-04-15 NA NA
3 BR073ELAC5EIANID-115781 2014-04-16 6 3
4 BR073ELAC5EIANID-115781 2014-04-17 5 2
5 BR073ELAC5EIANID-115781 2014-04-18 2 3
And I would like to add a column equal to 1 if column c = NA and if column d = NA I try the following :
df$e <- (if(is.na(df$c) && is.na(df$d)) 1 else 0)
but I get all the column e equal to 1
Upvotes: 0
Views: 1086
Reputation: 61154
You can avoid ifelse
, just use &
> df$e <- 1*(is.na(df$c) & is.na(df$d))
> df
a b c d e
1 BR073ELAC5EIANID-115781 2014-04-14 7 3 0
2 BR073ELAC5EIANID-115781 2014-04-15 NA NA 1
3 BR073ELAC5EIANID-115781 2014-04-16 6 3 0
4 BR073ELAC5EIANID-115781 2014-04-17 5 2 0
5 BR073ELAC5EIANID-115781 2014-04-18 2 3 0
Upvotes: 3
Reputation: 109844
Here's one approach using logical indexing:
as.numeric(is.na(df$c) & is.na(df$d))
## [1] 0 1 0 0 0
Upvotes: 1